Today’s tutorial, I will tell you about Refresh PartialView Automatically in ASP.NET MVC 6. First thing you can do is Create a MVC app on Visual Studio and then add two Classes to your model folder.
using System.ComponentModel.DataAnnotations;
namespace AutoRefresh.Models
{
public class Employee
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public string ImagePath { get; set; }
}
}
using System.Data.Entity;
namespace AutoRefresh.Models
{
public class DemoContext:DbContext
{
public DbSet<Employee> employee { get; set; }
}
}
Now, add a Home Controller and write the following code:
using System;
using System.Linq;
using System.Web.Mvc;
using AutoRefresh.Models;
using System.Web.UI;
namespace AutoRefresh.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
using (DemoContext dbObj = new DemoContext())
{
var empList = dbObj.employee.ToList();
return View(empList);
}
}
[OutputCache(Location = OutputCacheLocation.Client, VaryByParam = “none”, Duration = 2)]
public PartialViewResult _employeeShow()
{
using (DemoContext dbObj = new DemoContext())
{
var empList = dbObj.employee.ToList();
int MinId = empList.Min(a => a.Id);
int MaxId = empList.Max(a => a.Id);
//generate a random number
int GetRandomId = new Random().Next(MinId, (MaxId + 1));
var getRandomemployee=empList.Find(a => a.Id == GetRandomId);
return PartialView(“_employeeShow”, getRandomemployee);
}
}
}
}
From the above code, I used OutputCache to get Data from Cache. Next step, add a PartialView _employeeShow to show the Employee.
@model AutoRefresh.Models.Employee
<div class=”divEmployee” style=”margin-left: 50px;”>
<img src=”@Model.ImagePath” width=”100″ height=”100″ />
<span>@Model.Name</span>
</div>
Now , create the Index View. With this view we will load our PartialView.
@model IEnumerable<AutoRefresh.Models.Employee>
@{
ViewBag.Title = “Index”;
}
<script src=”~/Scripts/jquery-2.1.1.min.js”></script>
<script type=”text/javascript”>
$(document).ready(function () {
setInterval(function () {
$(‘#Employee’).load(‘/Home/_employeeShow’)
},2000);
});
</script>
<h2>Employee</h2>
<div id=”Employee”>
@Html.Partial(“_employeeShow”, Model.FirstOrDefault())
</div>
Using Jquery, I’m loading the PartialView in every 2 seconds.
HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.