我有一个控制器,它返回一个视图,并传递一个视图模型,该模型具有用于显示视图的属性(下拉选择项列表等)。
但是当我将它提交到服务器时,我有一个不同的模型类,它具有这些下拉框的所选值。在我的HttpPost控制器操作中,在执行任何处理之前,我检查(ModelState.IsValid),但当它为false时,我会'return View(model)'回来。
但由于该视图绑定到ViewModel上,而我的Post操作接受实际的模型,因此当我提交表单并且验证错误显示在视图上时,我会收到错误消息'The model item passed into the dictionary is of type 'Model', but this dictionary requires a model item of type 'ViewModel''。
如何解决这个问题?在使用强类型视图、传递视图模型但提交到不同模型的情况下,最佳实践是什么?
代码:
public ActionResult Buy()
{
BuyVM buyVM = GetBuyVM();
return View(buyVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Buy(BuyModel model)
{
if (ModelState.IsValid)
{
// Do Procesing
return View("Success");
}
return View(model);
}
public class BuyVM
{
public SelectList PurchaseDateList { get; set; }
public SelectList BedroomsList { get; set; }
public SelectList StoriesList { get; set; }
[Required]
public string SquareFootage { get; set; }
[Required]
public string PreferredCityLocations { get; set; }
public string AdditionalInfo { get; set; }
}
public class BuyModel
{
public string PurchaseDateList { get; set; }
public string BedroomsList { get; set; }
public string StoriesList { get; set; }
public string SquareFootage { get; set; }
public string PreferredCityLocations { get; set; }
public string AdditionalInfo { get; set; }
}
private static BuyVM GetBuyVM()
{
BuyVM buyVM = new BuyVM();
buyVM.PurchaseDateList = new SelectList(new[] { "Immediately", "1 to 3 months", "4 to 6 months", "More than 6 months" });
buyVM.BedroomsList = new SelectList(new[] { "1", "2", "3", "4", "5+" });
buyVM.StoriesList = new SelectList(new[] { "1", "2", "Does not matter" });
return buyVM;
}
Buy.cshtml
@model Models.BuyVM
// html
@Html.DropDownListFor(m => m.PurchaseDateList, Model.PurchaseDateList, new { @class = "form-control" })
@Html.DropDownListFor(m => m.BedroomsList, Model.BedroomsList, new { @class = "form-control" })
因此,当我在HTTPPost中返回View(model)时,如果有验证错误(JQueryVal),我尝试通过将模型传回视图来显示验证错误。但是我遇到了这种类型不匹配的问题。