What is Partial view
- A partial view is a portion of view content which is used to render some specific business UI which is common among some regular views. The partial view is shared among these regular views.
- A partial view is created using the same Razor View template which is used to create a standard view. A standard view is the view which is based on Action method view result.
- Same partial view can be used on multiple views (which may be regular view or layout view). Partial view follows DRY principle. Create once, use many times anywhere needed.
- A partial view has same file extension(.cshtml) as regular view. A view and partial view file extension depend on two things i.e. view engine and the programming language.
- Partial view cannot have HTML tags like HTML, head, title, body, meta because these are already defined in the layout view. It will have other HTML tags like h1, p, div etc. needed for the component. This fact is applicable on regular views also. We do not use Head part of HTML in regular view.
- A partial view is created inside Shared folder because it can be shared among standard views.
- As convention, partial view name begins with underscore.
- A partial view is a regular view which can be used on any view - regular or layout view.
- Note that other regular views must be rendered inside layout view if layout view is being used in the application but partial view can be applied on other views without using it on layout view.
- A partial view can be used on layout view to render common features such as navigation bar on multiple views.
- A partial view can be used on standard and layout views.
- File extension for Razor Partial View in C# is .cshtml.
- File extension for Razor Partial View in VB is .vbhtml.
- File extension for ASPX Partial View in C# or VB is .ascx.
How to Create Partial View in MVC?
How to Use Partial View in another normal view?
Look at the following code.
<div>
<partial name="_PVProgrammers" model="@Model"></partial>
</div>
The partial tag is used to insert a partial view into a normal view. Normal view is created for an action method of a controller. The partial tag can be inserted into normal view at any position as per the business need.
Applications of Partial view
- To provide common look and feel in different views portion but not for layout; instead for a business logic such as display list of items in the partial view.
- To refresh page without reloading in MVC; partial view is used to display data without refresh
- To fetch data from database without refreshing the page in ASP.NET Core
How to use partial view with AJAX jQuery
Example
- Project name: PartialViewCoreMvc
- Solution name: PartialViewCoreMvc
- .NET Core version: 6.0
- Microsoft.EntityFrameworkCore Version="6.0.0"
- Microsoft.EntityFrameworkCore.Design Version="6.0.0"
- Microsoft.EntityFrameworkCore.Tools Version="6.0.0"
- Microsoft.EntityFrameworkCore.SqlServer Version="6.0.0"
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"DefaultConnection": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=AppliedK4;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
},
"AllowedHosts": "*"
}
Create Programmer class in Models folder as given below.
namespace PartialViewCoreMvc.Models
{
public class Programmer
{
public int ProgrammerId { get; set; }
public string? ProgrammerName { get; set; }
public string? Language { get; set; }
}
}
Create ProgrammerViewModel class in Models folder as given below.
namespace PartialViewCoreMvc.Models
{
public class ProgrammerViewModel
{
public string? Name { get; set; }
public string? Language { get; set; }
}
}
Create a class called AppDbContext in Data folder in the solution explorer as shown below.
using Microsoft.EntityFrameworkCore;
using PartialViewCoreMvc.Models;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options) : base(options)
{
}
public DbSet Programmers { get; set; }
}
Run the following two commands in sequence using Tools > Nuget Package manager > Package manager Console.
- Add-Migration Initial
- Update-Database
Check that Migrations folder is created in the solution explorer. In this folder, a partial class named Initial will be created as per add-migration command.
- Database will be created as given in the appsettings.json file.
- Also, tables will be created in the database as per DbSet properties given in AppDbContext class file.
Now do the following.
- Delete HomeController available in Controllers folder in solution explorer.
- Delete Views/Home folder available in solution explorer.
- Create ProgrammerController in Controllers folder.
- Create Views/Programmer/Index view for Index action of the ProgrammerController.
- Install the Twitter-Bootstrap 4 version using Client Side Library.
- Rebuild the application by pressing CTRL+SHIFT+B
The ProgrammerController code is as follows.
using Microsoft.AspNetCore.Mvc;
using PartialViewCoreMvc.Models;
public class ProgrammerController : Controller
{
private readonly AppDbContext _dbcontext;
public ProgrammerController(AppDbContext applicationDbContext)
{
_dbcontext = applicationDbContext;
}
public IActionResult Index()
{
return View(_dbcontext.Programmers.Select(c => new ProgrammerViewModel() { Name = c.ProgrammerName, Language = c.Language }).ToList());
}
[HttpPost]
public IActionResult Create(ProgrammerViewModel model)
{
if (ModelState.IsValid)
{
_dbcontext.Programmers.Add(new Programmer() { ProgrammerName = model.Name, Language = model.Language });
_dbcontext.SaveChanges();
}
//after create new item, requery the database and return the ProgrammerList partial view to update the list.
return PartialView("_PVProgrammers", _dbcontext.Programmers.Select(c => new ProgrammerViewModel() { Name = c.ProgrammerName, Language = c.Language }).ToList());
}
}
The Index view code is as follows.
@model List<PartialViewCoreMvc.Models.ProgrammerViewModel>
@{
ViewData["Title"] = "Index";
}
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="Name" class="control-label">Name</label>
<input name="Name" id="txtname" class="form-control" />
</div>
<div class="form-group">
<label for="Language" class="control-label">Language</label>
<input Name="Language" id="txtLanguage" class="form-control" />
</div>
<br/>
<div class="form-group offset-6">
<input type="button" id="submit" value="Add New Programmer" class="btn btn-primary" />
</div>
</div>
</div>
<br/>
<div id="itemlist">
<partial name="_PVProgrammers" model="@Model"></partial>
</div>
@section Scripts{
<script>
$(function () {
$("#submit").click(function () {
var ProgrammerViewModel = {}; //create an object
ProgrammerViewModel.Name = $("#txtname").val();
ProgrammerViewModel.Language = $("#txtLanguage").val();
var currentdate = new Date();
var datetime = "Last created: " + currentdate.getDate() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getFullYear() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
console.log(datetime);
$.ajax({
url: "@Url.Action("Create","Programmer")",
data: { model: ProgrammerViewModel }, //the name ("model") should be the same with the parameter's name in the controller.
type: "Post", //change the method to Post.
success: function (result) {
$("#itemlist").html("");
$("#itemlist").html(result);
},
error: function (result) {
window.alert("This is an unhandled exception. ");
}
});
});
});
</script>
}
Code explanation.
In the index view, at the top is placed a form which is used to create new programmer. When user clicks the submit button, the jQuery AJAX function is run. The Date function is used just for debugging purpose. The ajax function calls the Create action. It sends the data as ProgrammerViewModel which is received by the Create action. The data name must match the Create parameter i.e. ProgrammerViewModel. Note that Create action returns a PartialView with model data. The model data in Index view is of IList type. The list is updated in the Index view after each create action call. In the Index view, at the bottom, partial view is placed which will render the list of all programmers. To list the existing programmers, Index action is called when the application is run.
Run the application by pressing F5 or CTRL+ F5. We get the following output.
No comments:
Post a Comment