有一个Index控制器,在其中我将数据库中的数据与modelview关联起来,而我的View收集并显示用户数据。因此,下面我将附加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的数据? 谁处理的?
答案 0 :(得分:0)
会发生什么
在您的代码中,您没有为View提供所需的模型。
如果使用Html.RenderPartialAsync(viewName)
,则会自动将整个模型从主视图传递到局部视图。由于主视图的模型类型为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>