Partial Views and its use in ASP.NET MVC



Partial Views in MVC are used like user controls in ASP.NET Web form allows you to reuse and breakup large view into small parts so view look like structured way. They are reduce duplication of views content in single project. There is no Layout page for Partial Views.

If you have page containing several logical pieces, so we can use partial view for distributing complex logic into small parts.

Partial Views can be child of another partial views.

For Creating Partial Views there is no any other procedures, you can simply add one .cshtml file inside Views folder like below.



After selecting View menu in opened window, another window will open where you have to add View Name and there is one checkbox with label “Create as a Partial View”, you have to check it. Please see below image so you will get idea.




When you check the checkbox, automatically Layout selecting dropdown is disabled because Layout is only for main view not for partial views.

After click on “Add” button, your partial view is generated in the folder you selected for creating like below.



Now next step is to render partial view in the main view. So first go to main view and write single line like below in main view.

@Html.Partial("PartialView");

Like below image you have to add it in main View or in another partial view.



Now, run the application you will get the “Index” view with Partial View render in that like below image.



There are 3 method you can use to render partial view in the main view.


1.       Html.Partial(“PartialViewName”);

This is used for rendering partial view on the view. And it returns IHtmlString.  There is no need to write action method for this method to render partial view.

2.       Html.RenderPartial("PartialView");

This is another method for rendering html on main view. It returns void and it writes directly to response output stream.

For rendering partial view using RenderPartial method, you have to write like below code.

@{
Html.RenderPartial("PartialView");
}

3.       @Html.RenderAction(PartialView)

You can render partial view by using RenderAction method also. But for this you have to write action method like below. And from that action method you have to return the partial view.

public ActionResult ReturnPartialView()
                  {
                     return PartialView("PartialView");
                  }



For passing the data to the partial view you can add another parameters to the above methods like below
1.      Html.Partial(“PartialViewName”, PartialData);
2.      Html.RenderPartial("PartialView", PartialData);
3.  public ActionResult ReturnPartialView()
{
return PartialView("PartialView”, PartialData); 
}

Post a Comment

1 Comments

  1. provide source code with articles
    So that we can learn from that

    ReplyDelete