Layouts in MVC

Layouts are used when there is a need to maintain a consistent look across multiple views.(Example : Header and footer across views).They are similar to master pages in ASP.NET.

Important Methods in Layouts :

@RenderBody():

1.Renders View and all of its components in layout page.

2.There can be only one RenderBody in a layout page.

Capture

@Renderpage():

1.Renders the specified page in layout.It takes an argument that specifies the location of page.


@RenderPage("~/Views/yourpage.cshtml");

2.There can be multiple RenderPage method in layout.

@Sections:

Renders the content of page in specified region  in layout.


@section("nameofsection,false")

1.Requires name of the section.If not specified exception will be thrown.

2.IsRequired attribute in section method has to be set to false,if section is not mandatory for every view,else an exception will be thrown.

rendersection

 

 

 

 

 

 

#Areas in MVC

It is hard for maintaining the controllers and views as project grows,

Areas in MVC provides solution by letting you to have controller,model,view per module.

For instance if you have  four modules,you could have four areas with its own controller,model and view.

Capture.PNG
Areas in MVC

In the example above,There are two modules  ExecutiveSponsors and Users put into an area.

Accessing and Configuring the area:

1.You can define the routes for the controller in the Corresponding AreaRegistration.

2.To access the controller from the browser,you must append the area name before the controller.

i.e http: //yourdomainname /Areaname/Controller

Example :

http://localhost:/ExecutiveSponsor/Sample.

 

MVC Validation- Custom Server and Client Side

Server Side Validation :

MVC Provides custom validation  via ValidationAttribute and IValidatableObject.

Server Side Validation with ValidationAttribute :

To implement custom server side validation,we must inherit from ValidationAttribute. In the below sample,i have a custom validator that checks if date is greater than todays date.


public class ValidateDate : ValidationAttribute
{
public ValidateDate()
{
ErrorMessage = "Date Time Cannot be greater than today's date";
}
public override bool IsValid(object value)
{
var datetime = Convert.ToDateTime(value);
if (datetime > DateTime.Now)
{
return false;
}
return true;
}

}

Usage : To use the above attribute,its enough to annotate over the property.


public class SampleModel
{
[Required]
[ValidateDate] //-----Custom Validator------//
public DateTime StartdateTime { get; set; }
}

As you can see above the validation works only after post back(after submit button) and the validation happens in server side.

Handling Custom Validation from Client Side :

Apart from javascript validation over model,mvc also provides custom validation from client side.

Implementing custom client side validation :

IClientValidatable interface indicates the mvc framework that the cutom validator supports client side validation. It provides a contract named  IEnumerable<ModelClientValidationRule> GetClientValidationRules that is responsible for returning validation rules in client side.

In the code below is the custom client side validator that implements IClientValidatable interface which displays an error message when date is greater than today’s date.


[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
 public class ValidateDate : ValidationAttribute,IClientValidatable
 {
 public ValidateDate()
 {
 ErrorMessage = "Date Time Cannot be greater than today's date";
 }
 public override bool IsValid(object value)
 {
 var datetime = Convert.ToDateTime(value);
 if (datetime &gt; DateTime.Now)
 {
 return false;
 }
 return true;
 }

public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
 {
 var modelvalidtorrule = new ModelClientValidationRule();
 modelvalidtorrule.ValidationType = "dategreaterthan"; //---will be used in registering with jquery adaptor---//
 modelvalidtorrule.ErrorMessage = ErrorMessage;
 return new[] {modelvalidtorrule};
 }
 }

Registering the Custom Validator with Jquery Adaptor :

Inorder to achieve the client side validation,we must add and register to jquery validator and adapters. 

Adding custom validator to Jquery Validator :


jQuery.validator.addMethod('dategreaterthan', function (value, element, params) {
 var currentDate = new Date();
 if (Date.parse(value) &gt; currentDate) {
 return false;
 }
 return true;
 }, '');

Adding custom Validator to Jquery Adaptor :


jQuery.validator.unobtrusive.adapters.add('dategreaterthan', function (options) {
options.rules['dategreaterthan'] = {};
options.messages['dategreaterthan'] = options.message;
});

Capture

 

 

HttpHanlder Vs HttpModule

HttpHandler: 

1.They are process which run when a request is made by client. Handlers include extension like (.aspx,.ashx).

2.We can implement custom Handler by implementing IHttpHanlder (ProcessRequest and IsReusable method)

Life cycle of HTTPHandler is only till the request is made.

HTTPModule : 

1.They are events which can be used even before page load /request is made to the server. 2.HTTP Module can be used for the entire life cycle of MVC where as HTTPHandler is valid only for handling request.

3.We can implement custom Module by implementing IHTTPModule(Init and Dispose Methods)

 

 

#Routing Constraint

Route Constraint : Restrict browser request that matches route value based on constraints.

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
constraints : new {id = @"\d"} // Constraint
);

The above constraint allows only integer to be passed,if a string is passed you
would get “No Resource Found“.If constraint is not handled,the page would have
throwed exception saying String could not be converted to string.thus constraint
also helps to hide sensitive information to client.
 

#11 Bind Attribute in MVC

There are cases where you want to limit/restrict  the properties of a model that is submitted to the server.

Model class :


[Bind(Exclude="Rid")] ---- Rid properties is excluded from model.

public class ReviewModel

{
public int Rid { get; set; } -- AutoGenerated ,User need not submit it
public String RName { get; set; }
public String RLocation { get; set; }
public int Rating { get; set; }
}

In the above example,Rid is Auto generated and user need not submit it when posted from View. Rid is excluded by using Bind attribute annotation. 

 

 

#10 RenderSection Method in Layout

In layout Pages,renders the content of named Section.

RenderSection("footer",false) ---If set to false,then view need not have a section

The above code expects the Section “footer” to be used and its mandatory,so typically view must have a section named footer.

{
    Layout = ~/Views/Shared/_Layout.cshtml;
}
section footer
{
This is sample footer
}

Working principle of RenderSection :

rendersection