#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

#7 Implementing Custom Error Attributes

We can implement Custom Error Handling attribute by implementing ActionFilterAttribute.It has Four methods OnActionExecuted,OnActionExecuting,OnResultExecuted,OnResultExecuting methods which would be overridden in custom class.


class LogAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
}

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
}

public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
}

public override void OnResultExecuting(ResultExecutingContext filterContext)
{
base.OnResultExecuting(filterContext);
}
}

#6 Handling Error in MVC-HandleErrorAttribute

By Default if an exception occurs in action method,it bubbles up to the FilterConfig which holds the  HandleError that is responsible for catching the exception.Framework also provides a View named “Error.cshtml” in shared folder that is responsible to show the exceptions in UI.


public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}