[英]Getting “No parameterless constructor defined for this object.” Error while posting a viewmodel
[英]Error “No parameterless constructor defined for this object.” with SelectList from ViewModel
在我的視圖模型中,我創建了兩個SelectList屬性,這些城市的名稱來自外部數據庫。
視圖模型
namespace Treinreizen.Models.ViewModels
{
public class ReizenViewModel
{
public SelectList VanStad { get; set; }
public SelectList NaarStad { get; set; }
}
}
在我的控制器中,我使用一種GET方法“ Registratie”,用戶可以在其中選擇城市,並使用一種POST方法來發布該城市。 問題是我得到了錯誤
“沒有為此對象定義無參數構造函數。”
當我嘗試發布表格時。 在堆棧跟蹤中說:
“ [[MissingMethodException:沒有為此對象定義無參數構造函數。]”和“ [[MissingMethodException:沒有為此對象定義無參數構造函數。對象類型'System.Web.Mvc.SelectList'。]”
調節器
// GET: Hotels/Registratie
public ActionResult Registratie()
{
stedenServices = new StedenServices();
ReizenViewModel registratieviewmodel = new ReizenViewModel();
registratieviewmodel.VanStad = new SelectList(stedenServices.All(), "StadID", "Stad");
registratieviewmodel.NaarStad = new SelectList(stedenServices.All(), "StadID", "Stad");
return View(registratieviewmodel);
}
// POST: Hotels/Registratie
[HttpPost]
public ActionResult Registratie(ReizenViewModel registratie)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index");
}
return View(registratie);
}
視圖
<div class="form-group">
@Html.LabelFor(model => model.VanStad, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.VanStad, Model.VanStad, "--Selecteer Stad--")
@Html.ValidationMessageFor(model => model.VanStad, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.NaarStad, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(m => m.NaarStad, Model.NaarStad, "--Selecteer Stad--")
@Html.ValidationMessageFor(model => model.NaarStad, "", new { @class = "text-danger" })
</div>
</div>
只需向ReizenViewModel添加一個無參數的構造函數即可:
public ReizenViewModel(){}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.