C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ASP.NET Razor Partial ViewsASP.NET provides a facility to create reusable components so that, that can be shared in the web application. These sharable components are known as partial views. A partial view is a view which can be plugged in parent view. This view file has the same extension as other views have .cshtml. When Should We Use Partial Views?When having a large view file that contains several logical sections, we can break it into smaller components that further can be rendered as partial view. Note:- Razor views works on DRY (Don't Repeat Yourself) concept.ASP.NET provides following two methods to render partial view.
Both the methods are used to render partial view, except that the RenderPartial() has void return type. RenderPartial() has better performance than Partial(). Creating a Partial ViewTo create a partial view, right click on the Views folder or subfolder of it then add view as we did in the following screenshot. After adding, it creates a file PartialViewDemo.cshtml that contains no productive code. We have a view that contains some HTML source. We want to render created partial view in this file. Let's see how do we do this? Our view file contains the following source code. // Registration.cshtml @{ ViewBag.Title = "User Registration Form"; } <hr /> <h3>User Registration Form</h3> <hr /> <div class="form-horizontal"> @using (Html.BeginForm("Registration","Students")) { <div class="form-group"> @Html.Label("User Name", new { @class = "control-label col-sm-2" }) <div class="col-sm-10"> @Html.TextBox("username", null, new { @class = "form-control" }) </div> </div> @Html.Partial("PartialViewDemo") <div class="form-group"> <div class="col-sm-2"></div> <div class="col-sm-10"> <input type="submit" value="submit" class="btn btn-primary" /> </div> </div> } </div> PartialViewDemo.cshtml <div class="form-group"> @Html.Label("Email ID", new { @class = "control-label col-sm-2" }) <div class="col-sm-10"> @Html.TextBox("email", null, new { @class = "form-control" }) </div> </div> The Registration page contains single text box component, the PartialViewDemo page contains second text box. The @Html.Partial() method is used to render partial view to the Registration view. Output: It produces the following output when, we run the registration page. We can submit it as a single form. This form submits all the values to the action that are shown in the following screenshot.
Next TopicASP.Net Interview Questions
|