Friday, February 10, 2012

Partial Views in ASP.NET MVC 3

Generally, the coding that we type in the .cshtml or .vbhtml file in a MVC 3 view is rendered through a view engine. Before MVC 3 come into action, ASPX was the View engine used to render the content. MVC 3 introduces a new view engine named Razor. Razor is an effective rendering engine that is introduced with ASP.NET MVC 3. It has simplified syntax along with the easy and cool capabilities provided for the developer to use with. It is easy to use and will not get complicated with the syntax that was available in ASPX View engine.
A much descriptive article on Razor syntax is available at the MSDN.
If you create a View in ASP.NET MVC, it will allow you to create one of the CRUD operations that you would like to have. How are we going to add another operation of the same entity or another in the same View. There are 2 ways that it can be done. We can add a User Control or a Partial View. Both looks like same for a particular extent. User controls have an implementation of events whereas partial views do not.
Creating a Partial View is not that big thing. You just need to try adding a View by right-clicking on the sub folder under the Views folder. Then the Add View window will open. It is advised that the partial views must start with “_” prefix. It makes it easy to identify that as a partial view. Then click the checkbox in front of the Create as a partial view. Since I do have created a model class in my project, I can select it as the model. The way how Model can be modeled is described in a previous article.
Then the partial view will be created. Now it’s time to add it into a View. Just go to the view that you would like to add the partial view and type,
1
@Html.Partial("_Index")
Then the content in the created partial view will appear in the View where it is defined to be located. There are some minor issues when having two forms in both partial view and the View. For example adding the User and adding aProduct in the same. Lets discuss more about Partial views and the ways how it can be done in an upcoming article.

No comments:

Post a Comment