类型的模型项在执行当前Web请求期间生成未处理的异常。关于异常的来源和位置的信息可以使用下面的异常堆栈跟踪来标识。ASP.NET MVC 5传入字典的模型项目类型为'Name.Models.IndexViewModel',但该字典需要
堆栈跟踪:
出现InvalidOperationException:传递到字典 类型为“Name.Models.IndexViewModel”的模型项目,但这个字典 需要类型的模型项目“Name.Models.TwoViewModel ”。
我需要为这个视图中的两个不同的视图模式:
public class TwoViewModel
{
public IEnumerable<Name.Models.Project> Model1 { get; set; }
public IndexViewModel Model2 { get; set; }
}
编辑:
我想我已经找到了其中的问题从何而来,该ManageController:
public async Task<ActionResult> Index(ManageMessageId? message)
{
var userId = User.Identity.GetUserId();
var userEmail = User.Identity.Name;
var user = UserManager.FindById(userId);
var model = new IndexViewModel
{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
City = user.City,
};
return View(model);
}
我试图改变模型的ViewModel,尝试像
var model = new TwoViewModel
{
Model2.Email = user.Email,
Model2.FirstName = uesr.FirstName,
Model2.LastName = user.LastName,
Model2.City = user.City,
};
return View(model);
而intellisense确实承认Model2而不是.Email部分。我认为嵌套会是这种情况?
我试过这种方法:
var model = new TwoViewModel
{
Model2 = new IndexViewModel
{
Email = user.Email,
FirstName = user.FirstName,
LastName = user.LastName,
City = user.City,
}
};
return View(model);
但随后另一件事给了不设置到对象的实例的
对象引用。
错误。
@foreach (var item in Model.Model1)
{
<tr>
<td>@Html.DisplayFor(modelItem => item.Title)</td>
....
</tr>
}
This @foreach (var item in Model.Model1
)line is the cause of the problem。现在语法很好。我有这条线可以从第一个模型(IEnumerable<Name.Models.Project>
)中检索所有的东西,没有任何问题。我不知道如何处理这个错误
编辑:解决方案是,我必须在ManageController内的类型TwoViewModel模型内初始化模型1。这固定我的错误
[如何创建一个最小,完整和可验证示例](http://stackoverflow.com/help/mcve) –
错误消息是不言自明的。你有'@model TwoViewModel'的视图,但是你在某处传递一个模型到这个视图,这个视图是'IndexViewModel' –
好吧,我将添加所有代码,然后才能重现问题 – crystyxn