我正在学习如何使用ViewModels将信息从视图传递到控制器,反之亦然。我的创建操作,视图和视图模型完美地工作,但我在编辑时遇到问题。我收到错误:
传递到字典中的模型项的类型为“CatVM.Models.Cat'”,但此字典需要类型为' CatVM.Models.EditCatViewModel'的模型项。
这是我的代码:
控制器方法
// GET: /Cats/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Cat cat = unitOfWork.CatRepository.GetByID(id);
if (cat == null)
{
return HttpNotFound();
}
return View(cat);
}
查看
@model CatVM.Models.EditCatViewModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Cat</h4>
<hr />
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.ID)
<div class="form-group">
@Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Color, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Color)
@Html.ValidationMessageFor(model => model.Color)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.FurLength, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FurLength)
@Html.ValidationMessageFor(model => model.FurLength)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Size, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Size)
@Html.ValidationMessageFor(model => model.Size)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
EditCatViewModel
public class EditCatViewModel
{
public int ID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(50)]
public string Color { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Fur Type")]
public string FurLength { get; set; }
[StringLength(50)]
public string Size { get; set; }
}
}
答案 0 :(得分:1)
这是因为您从CatRepository.GetByID(id);
收到的项目属于Cat
,而不是EditCatViewModel
。
您可以通过从此对象构建新的viewmodel来绕过此问题:
Cat cat = unitOfWork.CatRepository.GetByID(id);
var viewModel = new EditCatViewModel {
Name = cat.Name,
Color = cat.Color,
FurLength = cat.FurLength,
Size = cat.Size
};
return View(viewModel);
或者,您可以构建implicit或explicit投射方法或使用AutoMapper之类的地图工具。
答案 1 :(得分:0)
您的返回视图应为CatVM.Models.EditCatViewModel类型,现在您返回Cat
返回视图(cat);
在视图模型中转换模型并将此对象传递回视图