有一个索引控制器,其中我将数据库中的数据与模型视图相关联,我的视图收集用户数据并显示它。因此下面我将附上PartialView
public class CustomerController : Controller
{
private ICustomerRepository _customerRepository;
public CustomerController(ICustomerRepository customerRepository)
{
_customerRepository = customerRepository;
}
[HttpGet]
public IActionResult Index()
{
IEnumerable<CustomerViewModel> customers =
_customerRepository.GetAllCustomers().Select(s => new
CustomerViewModel
{
CustomerId = s.CustomerId,
Name = s.Name,
Adress = s.Adress
});
return View("Index", customers);
}
[HttpGet]
public IActionResult Create()
{
return Redirect("Index");
}
}
@model IEnumerable<CustomerViewModel>
<h2>Create Customer</h2>
@{
await Html.RenderPartialAsync("Create");
}
<table class="table">
@Html.DisplayNameFor(model => model.Name)
@foreach (var item in Model)
{
@Html.DisplayFor(modelItem => item.Name)
}
</table>
这是PartialView本身:
@model CustomerViewModel
<div class="col-md-4">
<form asp-action="Create" asp-controller="Customer">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input type="text" asp-for="Name" class="form-control" />
</div>
应用程序启动时,会发生错误:
InvalidOperationException:传递给ViewDataDictionary的模型项的类型为'System.Linq.Enumerable + SelectEnumerableIterator` 2 [Store.DAL.Entity.Customer,Store.Web.ViewModels.CustomerViewModel]',但此ViewDataDictionary实例需要模型项输入'Store.Web.ViewModels。 CustomerViewModel
如果将partialView放在单独的页面上,只需创建一个指向View的链接,就会显示所有内容并且不会出现错误。也许这就是我如何在Controller中覆盖customerViewModel的数据?谁处理了这个?
怎么了
在您的代码中,您没有为View提供所需的模型。
如果使用Html.RenderPartialAsync(viewName)
,则会自动将整个模型从主视图传递到partial。由于主视图具有IEnumerable<CustomerViewModel>
的模型类型 - 这是传递给局部视图的内容。
解决方案
Html.RenderPartialAsync(string viewName, object model)
的重载来正确传递模型。对于解决方案#2,示例代码可以是:
新课
public class CustomerListViewModel
{
IEnumerable<CustomerViewModel> existingCustomers;
CustomerViewModel newCustomer;
}
调节器
[HttpGet]
public IActionResult Index()
{
IEnumerable<CustomerViewModel> customers =
_customerRepository.GetAllCustomers().Select(s => new
CustomerViewModel
{
CustomerId = s.CustomerId,
Name = s.Name,
Adress = s.Adress
});
CustomerListViewModel model = new CustomerListViewModel
{
existingCustomers = customers.AsEnumerable();
newCustomer = new CustomerViewModel();
}
return View("Index", model);
}
主要观点
@model CustomerListViewModel
<h2>Create Customer</h2>
@{
await Html.RenderPartialAsync("Create", Model.newCustomer);
}
<table class="table">
@foreach (var item in Model.existingCustomers)
{
<tr>
<td>@Html.DisplayFor(item => item.Name)</td>
</tr>
}
</table>