Search

Tuesday, February 25, 2014
0 comments

About the Default Action Methods in MVC Controller

8:58 AMTuesday, February 25, 2014
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>

<h2>Index</h2>
<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.Id })
        </td>
    </tr>
}
</table>

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

Protected by Copyscape Online Copyright Protection Software

0 comments :

Post a Comment

 
Toggle Footer
Top