Friday, 5 July 2013

Partial View in Asp.Net MVC4

If you want to reuse a view in your web application, you can go for partial view concept. Partial view is like regular view with file extension .cshtml.We can use partial view when the situation like we need a header, footer reuse for the mvc web application. We can say that it’s like a user control concept in
Here i am going to explain how to create a partial view in mvc 4 application.
First add a view to shared folder with view name _Product .the best way to create partial view with name preceded by '_', because the name specifying that it is reusable.

Here in this example, I am using the partial view to display the item selected in the webgrid.
Creating  webgrid example is in below link:
Add html controls in partial view fir display the selected item.

            @Html.TextBox("Id", Model.Id)
            @Html.TextBox("Name", Model.Id)
            @Html.TextBox("Description", Model.Description)
            @Html.TextBox("Quantity", Model.Quantity)

We can call the partial view in a normal view like:

Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);
@Html.Partial("~/Views/Shared/_Product.cshtml", product);

Html.Partial returns a string, Html.RenderPartial calls Write internally, and returns void. You can store the output of Html.Partial in a variable, or return it from a function. You cannot do this with Html.RenderPartial.Because the result will be written to the Response stream during the execution. So @html.RenderPartial() has fast execution than @html.Partial() due to RenderPartial give quick response to Output.
We can call the partial view if grid have any selected item. The code block is here:

@if (grid.HasSelection)
             product =(PartialViewSample.Models.Product)grid.Rows[grid.SelectedIndex].Value;       
             Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);          
In the above if you want to send the selected item into an action you can add a column with action link and send the selected item.

grid.Column("Detail", format: @<text>@Html.ActionLink("Select", "Submit", new { QtId = item.QtId }) </text>)

And in the action get the  selected item and pass as parameter to display view.

public ActionResult Submit(Product product)
   return View(product);