Dot Net For All

ASP.NET MVC Partial View Best Example

In my previous article I have discussed about the display of data collection, editing of data uaing HTTPPOST and routing in ASP.NET MVC. In this article I want to discuss about the asp,net mvc partial view. How to create partial view and where to use them. A partial view allows to put the C# and HTMl code into the file which can be used across multiple views in the same application. In the end of the article I will show the use of ChildActionOnly attribute for the action methods.

In my one of the article I have created a view for displaying the the list of all the students in the view, the code of which is shown below. We want to be consistent and do not want to use the same code every time we want to display the details of a student.

@model IEnumerable<StudentInfo.Models.Student>

@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.TotalMarks)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.LastName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.TotalMarks)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { id=item.StudentID }) |
            @Html.ActionLink("Details", "Details", new { id=item.StudentID }) |
            @Html.ActionLink("Delete", "Delete", new { id=item.StudentID })
        </td>
    </tr>
}

</table>

We will create a partial view under the View folder from the folder structure shown in this article. Right click on the Shared folder under Views folder and add a View named _StudentDetails.cshtml as shown in the figure 1.

Figure 1

And take all the code from the foreach code block from the above and paste it into the newly created view as shown in the code below.

@model StudentInfo.Models.Student

<tr>
    <td>
        @Html.DisplayFor(Model => Model.FirstName)
    </td>
    <td>
        @Html.DisplayFor(Model => Model.LastName)
    </td>
    <td>
        @Html.DisplayFor(Model => Model.TotalMarks)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = Model.StudentID }) |
        @Html.ActionLink("Details", "Details", new { id = Model.StudentID }) |
        @Html.ActionLink("Delete", "Delete", new { id = Model.StudentID })
    </td>
</tr>

The underscore in the view name denotes that it is a special view and in this case it is a partial view. As seen in the figure 1 above the Model is still the Student class while creating this new view. One more thing you can notice from the figure is that I have selected the option create as partial view which means that visual studio wont add the code block at the top of the page to set the page title which is the responsibility of the content view.

As you can see from the above code that I have replaced the item with Model as I have copied the code from the main view and I have to change the code of the main view for the foreach as shown in the code block below.

@foreach (var item in Model) {
    @Html.Partial("_StudentDetails", item)
}

Now we can see that the above code is more condensed form and it is very easy for the developer to see that some _StudentDeatils view is being rendered in this part of the code.

Here I am passing the name of the view and the model which the view will be bind to.

There is one more scenario when we want to use the partial views. In the above case we have passed the model class for the partial View as that is the only information that we can pass from the parent view or we can pass some property of the model class but there can be cases where we do not have a model to be bind to the partial view and we still want that single view to be displayed across the application.

For example if we want to add a partial view in the _layout.cshtml which will display the top rank student across all the application and it is very difficult to tie it to any particular model as Layout.cshtml does not have any model associated to it.

There is another helper present for this type of scenario which we can call to render partial view when we do not have any model information present with us. This method is know in Action method present for the HTML helpers. The implementation of this is shown in the below figure in the _layout.cshtml

Action Method for Partial View

In the figure you can see that I have mentioned the action and the controller name which are “BestStudent” and “Student” respectively in my case. Here I want to point out that it is not a seperate request but it is a sub request which will call this action in the controller. In the student controller I have implemented the BestStudent action as shown in the code below.

        [ChildActionOnly]
        public ActionResult BestStudent()
        {
           
            var editedStudent = studentList.OrderByDescending(item => item.TotalMarks).First();
            return PartialView("_StudentDetails", editedStudent);           
        }

I have added the above action as part of my StudentController. As you can see in the code I am calling a PartialView method which helps me to render a particular partial view and this method knows that the request to this BestStudent() method is not a separate request but it is a part of the main request. While calling asp.net mvc Partial VIew method I am passing the name of the partial view which I have already created along with the object.

ChildActionOnly – Since this method is a public method there are chances that the end user can call this method through URL and can be utlized in mischeviois way. To prevent this method to be called from the URL as main request we use the ChildActionOnly attribute so that this action can be called as sub request and not the main request.

After doing these changes if I run the view I can see the that a partial view has been injected in all the pages where ever I go in the application as shown in below figures.

 

 

 

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview