这个问题在这里已有答案:
我正在使用.net core 2.0(preview2)来构建一个 MVC Web 应用程序。我要做的是让网页的一部分在一定的时间间隔内刷新,以便加载新数据。 (出于这个例子的目的,它只是输出 DateTime.Now)
这是我到目前为止所得到的:
index.cshtml(主视图)
<div id="content">
@Model.name
@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(模型 1)
using System;
namespace DemoApp.Models
{
public class CustomersViewModel
{
public string name { get; set; }
public string city { get; set; }
}
}
Employee.cshtml(部分视图)
@model EmployeeViewModel
<div id="employeeContent">
Hello Employees!
@Model.employeeName
@Model.employeeCity
@Model.time
</div>
EmployeeViewModel.cs(模型 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(控制器 2)
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();
}
}
}
如您所见,我正在尝试从局部视图内的 EmployeeController 显示 Index()中的逻辑数据。要检查它是否有效,应显示当前的 date/time。
有了这个状态,我得到错误:
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'.
我在这里尝试了很多不同的东西,但实际上并没有什么帮助。当然,我避免了错误消息,但后来我无法将任何数据加载到局部视图中。
我从哪里开始,我错过了什么?
编辑:这根本不是完全相同的。重复链接指的是 MVC 中的某些内容,但不是.net 核心 MVC 中的内容,其中@Html.Action 不存在。但链接确实有帮助:-)
1 回答
您需要更改 EmployeeController: