I'm using .net core 2.0 (preview2) to build a MVC web app. What I'm trying to do is to have a part of the web page to refresh on a certain interval, so that new data will be loaded. (For the purpose of this example, it's just the output DateTime.Now)
Here's what I've got so far:
index.cshtml (Main View)
<div id="content">
@Model.name
<br />
@Model.city
<div id="employee">@Html.Partial("Employee")</div>
</div>
<script>
$(document).ready(function () {
var url = "@(Html.Raw(Url.Action("Index", "Employee")))";
$("#employee").load(url);
setInterval(function () {
var url = "@(Html.Raw(Url.Action("ActionName", "Employee")))";
$("#employee").load(url);
}, 1000); //Refreshes every second
$.ajaxSetup({ cache: false }); //Turn off caching
});
</script>
HomeController.cs (Controller1)
using System;
using Microsoft.AspNetCore.Mvc;
using DemoApp.Models;
namespace DemoApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
CustomersViewModel customers = new CustomersViewModel();
customers.name = "John";
customers.city = "New York";
return View(customers);
}
}
}
CustomerViewModel.cs (Model 1)
using System;
namespace DemoApp.Models
{
public class CustomersViewModel
{
public string name { get; set; }
public string city { get; set; }
}
}
Employee.cshtml (Partial view)
@model EmployeeViewModel
<div id="employeeContent">
Hello Employees!
<br />
@Model.employeeName
<br />
@Model.employeeCity
<br />
@Model.time
</div>
EmployeeViewModel.cs (Model 2)
using System;
namespace DemoApp.Models
{
public class EmployeeViewModel
{
public string employeeName { get; set; }
public string employeeCity { get; set; }
public string time { get; set; }
}
}
EmployeeController.cs (Controller2)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DemoApp.Models;
namespace DemoApp.Controllers
{
public class EmployeeController : Controller
{
public IActionResult Index()
{
EmployeeViewModel evm = new EmployeeViewModel();
evm.employeeName = "Jack";
evm.employeeCity = "Los Angeles";
evm.time = DateTime.Now.ToString();
return View();
}
}
}
As you can see, I'm trying to show data from the logic in Index() from the EmployeeController inside the partial view. To check if it works, the current date/time should be showed.
With this state, I get the error:
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'DemoApp.Models.CustomersViewModel', but this ViewDataDictionary instance requires a model item of type 'DemoApp.Models.EmployeeViewModel'.
I tried a lot of different things I found here, but actually nothing really helped. Sure, I avoided the error message, but then I wasn't able to load any data into the partial view.
Where do I go from here, what am I missing?
EDIT: This is not an exact duplicate at all. The duplicate link refers to something in MVC, but not in .net core MVC, where @Html.Action doesn't exist. But the link did help :-)