About the Default Action Methods in MVC Controller

Earlier article was about to add a controller (Student) and create its default views (having the same name as default actions). In this article we will discuss about the Index action which is used to show the list of particular table in database or any list container.

The index action by default have following code:
private StudentContext db = new StudentContext();
public ActionResult Index()
return View(db.Students.ToList());

In this code the first line is used to create the object of Student context class, which is used further to perform CRUD actions with the database. This action is simply a method having return type ActionResult which is basically encapsulates the result of an action method and used to perform a framework-level operation on behalf of the action method.

Just get in to the inner code of this action, having a single line of code, which is returning the view with the list of students stored in the database (from the db variable initialized in the first line).

Open the Index view in the Views>> Students folder having something like the below code:

@model IEnumerable<MvcApplication1.Models.Student>

            @Html.DisplayNameFor(model => model.Name)
@foreach (var item in Model) {
            @Html.DisplayFor(modelItem => item.Name)
            @Html.ActionLink("Edit", "Edit", new { id=item.Id })

The first line contains the name of model specifying that this view is strongly typed view of the named mode. The total body of this view is in table written above. Table headers are bind with the model fields, it may be a simple string.

After the headers a loop is there for all the items contained in the model. The DisplayFor() method is used to show the value of name of item passed through the model and more fields have more headers as well as other fields.

GET and POST Create Action in MVC


Post a Comment