【发布时间】:2017-04-13 23:12:48
【问题描述】:
在我的视图模型中,我使用来自外部数据库的城市名称创建了两个 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>
【问题讨论】:
-
这不是 MVVM,它是 MVC,因此“asp.net-mvc”。ReizenViewModel 不是视图模型,而是模型。你混合了两种不同的模式。
标签: c# asp.net-mvc