RenderPage and RenderBody

RenderPage
RenderPage method also exists in the Layout page to render other page exists in your application. A layout page can have multiple RenderPage method.
@RenderPage(“~/Views/Shared/_Header.cshtml”)

RenderBody
RenderBody method exists in the Layout page to render child page/view. It is just like the ContentPlaceHolder in master page. A layout page can have only one RenderBody method.
@RenderBody()

Advertisements

Return types of a controller action method

The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.

ActionResult Helper Method Description
EmptyResult (None) returns a null result
FileResult File Returns a binary output to write to the response
JavaScriptResult JavaScript Returns a script that can be executed on the client
JsonResult Json When you want to return a serialized JSON object
ContentResult Content Returns a user-defined content type
RedirectToRouteResult RedirectToRoute Redirect to another action method
RedirectResult Redirect When you want to redirect to another action method we will use RedirectResult
PartialViewResult PartialView As the name describe PartialViewResult renders the partial view.
ViewResult View ViewResult Renders a view as a web page.

PartialView As the name describe PartialViewResult renders the partial view.
RedirectResult Redirect When you want to redirect to another action method we will use RedirectResult
RedirectToRouteResult RedirectToRoute Redirect to another action method
ContentResult Content Returns a user-defined content type
JsonResult Json When you want to return a serialized JSON object
JavaScriptResult JavaScript Returns a script that can be executed on the client
FileResult File Returns a binary output to write to the response
EmptyResult (None) returns a null result

Validation using Data Annotation

Decorate model with data annotation=>

using System.ComponentModel.DataAnnotations;

Let’s say we have a customer model and we want to ensure that the customer code field is compulsory. So you can apply the attribute “Required” as shown in the below code snippet. If the validation fails and you would like to display some error message, you can pass the “ErrorMessage” also.

public class Customer
{
[Required(ErrorMessage=”Customer code is required”)]
public string CustomerCode
{
set;
get;
}
}

Data Annotations in MVC

The following are the Data Annotations we can use in a Model:
DisplayName: Provides a general-purpose attribute that lets you specify localizable strings to display.
Required: A value is required
DataType: The data type annotation can be used to specify the data type for validation.
StringLength: Max. length of an array or string data allowed.
DisplayFormat: Specify the display format for a property like various formats for the Date property.
ReqularExpression: Validate the value of a property by specifyng a regular expression pattern.
Range: Numeric range constraints for the data field value.
MaxLength: Specify max length for a string property.
Bind: Specify fields to include or exclude when adding parameter or form values to model properties.
Compare: The Compares property compares two properties
Key: Denotes one or more properties that uniquely identify an entity.

HTML helper methods

It helps you to render HTML controls in the view. For instance, if you want to display an HTML textbox on the view, below is the HTML helper code.

<%= Html.TextBox(“LastName”) %>
<%= Html.TextArea(“Profile”, new {cols=60, rows=10})%>

Example of BeginForm()

@using (Html.BeginForm())
{
@Html.TextBox(“Name”);
@Html.Password(“Password”);
<input type=”submit” value=”Sign In”>
}

Example of EndForm()

@{ Html.BeginForm(); }
//Stuff in the form
@{ Html.EndForm(); }

Example of TextArea()

<%= Html.TextArea(“Profile”, new {cols=60, rows=10})%>

Example of TextBox()

<%= Html.TextBox(“LastName”) %>

Example of CheckBox()

<%= Html.CheckBox(“Married”) %>

Example of RadioButton()

<label>@Html.RadioButton(“ABC”, True)Yes</label>
<label>@Html.RadioButton(“ABC”, False)No</label>

Example of ListBox()

@{
var items = new List<SelectListItem>{
new SelectListItem {Value = “1”, Text = “Blue”},
new SelectListItem {Value = “2”, Text = “Red”},
new SelectListItem {Value = “3”, Text = “Green”, Selected = true},
new SelectListItem {Value = “4”, Text = “Yellow”, Selected = true},
new SelectListItem {Value = “5”, Text = “Black”}
};
}

@Html.ListBox(“myListbox”, items, null, 6, true)

Example of DropDownList()

@{
var db = Database.Open(“Northwind”);
var data = db.Query(“SELECT CategoryId, CategoryName FROM Categories”);
var items = data.Select(i => new SelectListItem {
Value = i.CategoryId.ToString(),
Text = i.CategoryName,
Selected = i.CategoryId == 4 ? true : false
});
}

@Html.DropDownList(“CategoryId”, items)

Example of Hidden()

@Html.Hidden(“Name”, “Value”)

Example of Password()

<%= Html.Password(“Password”) %>

 

MVC Request Life Cycle

  • Routing

Asp.net Routing is the first step in MVC request cycle. Basically, it is a pattern matching system that matches the request’s URL against the registered URL patterns in the Route Table.

  • MvcHandler

The MvcHandler is responsible for initiating the real processing inside ASP.NET MVC. MVC handler implements IHttpHandler interface and further process the request by using ProcessRequest method

  • Controller

As shown in above code, MvcHandler uses the IControllerFactory instance and tries to get a IController instance. If successful, the Execute method is called.

  • Action Execution

Once the controller has been instantiated, Controller’s ActionInvoker determines which specific action to invoke on the controller. Action to be execute is chosen based on attributes ActionNameSelectorAttribute (by default method which have the same name as the action is chosen) and ActionMethodSelectorAttribute(If more than one method found, the correct one is chosen with the help of this attribute).

  • View Result

The action method receives user input, prepares the appropriate response data, and then executes the result by returning a result type. The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult.

  • View Engine

The first step in the execution of the View Result involves the selection of the appropriate View Engine to render the View Result. It is handled by IViewEngine interface of the view engine. By default Asp.Net MVC uses WebForm and Razor view engines.

  • View

Action method may returns a text string,a binary file or a Json formatted data. The most important Action Result is the ViewResult, which renders and returns an HTML page to the browser by using the current view engine.