Link for code samples used in the demo
Link for csharp, asp.net, ado.net, dotnet basics, mvc and sql server video tutorial playlists
In this video we will discuss partial views in mvc.
If you are an asp.net webforms developer, then you will realize that partial views in mvc are similar to user controls in asp.net webforms.
Partial views are used to encapsulate re-usable view logic and are a great means to simplify the complexity of views. These partial views can then be used on multiple views, where we need similar view logic.
If you are using web forms view engine, then the partial views have the extension of .ascx. If the view engine is razor and programming language is c#, then partial views have the extension of .cshtml. On the other hand if the programming language is visual basic, then the extension is .vbhtml.
Let us understand partial views with an example. We want to display, employee photo and his details.
Index Action() method in HomeController retrurns the list of employees.
public ActionResult Index()
SampleDBContext db = new SampleDBContext();
Index.cshtml is available on my blog at the following link. This view is a bit messy and complex to understand.
To simplify this view, let’s encapsulate the HTML and code that produces the employee table in a partial view.
Right click on the “Shared” folder and add a view. Set
View name = _Employee
View engine = Razor
Create a strongly typed view = Checked
Model class = Employee (MVCDemo.Models)
Scaffold template = Empty
Create as a partial view = Checked
This should add “_Employee.cshtml” partial view to the “Shared” folder.
Please note that, partial views can be added to “Shared” folder or to a specific views folder. Partial views that are in the “Shared” folder are available for all the views in the entire project, where as partial views in a specific folder are available only for the views with-in that folder.
“_Employee.cshtml” partial view code is available on my blog at the following link.
Now, make the following changes to Index.cshtml view. Notice that the view is much simplified now. To render the partial view, we are using Partial() html helper method. There are several overloaded versions of this method. We are using a version that expects 2 parameters, i.e the name of the partial view and the model object.
@foreach (var item in Model)
Xem thêm bài viết khác: https://wijstaanvooronzegrondrechten.org/cong-nghe