Jul 21, 2015

Partial View in ASP.NET MVC 4 ? How you create User Control in MVC application?

We can create a partial view and place that in shared folder. this partial view can be used as user control.

 If you want to reuse a view in your web application, you can go for the partial view concept. Partial view is like a regular view with a file extension .cshtml. We can use partial views in a situation where we need a header, footer reused for an MVC web application. We can say that it’s like a user control concept in ASP.NET.

Here I am going to explain how to create a partial view in an MVC 4 ASP.NET application.
First add a view to the shared folder with the view name _Product. The best way to create a partial view is with the name preceded by '_', because the name specifying that it is reusable.

 Add HTML controls in the partial view to display the selected item:


@model PartialViewSample.Models.Product

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>AddProduct</title>    
</head>
<body>
    <div>      
           <label>Id:</label>
            @Html.TextBox("Id", Model.Id)
             <label>Name:</label>
            @Html.TextBox("Name", Model.Id)
             <label>Description:</label>
            @Html.TextBox("Description", Model.Description)
             <label>Quantity:</label>
            @Html.TextBox("Quantity", Model.Quantity)
    </div>
</body>
 
</html>
 
 
We can call the partial view in a normal view like:
 
 
Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);
 
 
Or
 
@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 execution. So @html.RenderPartial() has faster execution than @html.Partial() due to RenderPartial giving quick response to the output.
We can call the partial view if the grid has a selected item. The code block is shown here:


@if (grid.HasSelection)
{
    product =(PartialViewSample.Models.Product)grid.Rows[grid.SelectedIndex].Value;        
    Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);           
}
 
 

 
  

No comments:

Post a Comment