我正在尝试学习 MVC 的基础知识(NerdDinner 教程)。我定义了一个模型:
public class DinnerFormViewModel
{
// Properties
public Dinner Dinner { get; private set; }
public SelectList Countries { get; private set; }
// Constructor
public DinnerFormViewModel(Dinner dinner)
{
Dinner = dinner;
Countries = new SelectList(PhoneValidator.Countries, dinner.Country);
}
}
我定义了一个局部视图:
@model MyNerddiner.Models.DinnerFormViewModel
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Dinner</legend>
@Html.HiddenFor(model => model.Dinner.DinnerID)
<div class="editor-label">
@Html.LabelFor(model => model.Dinner.Title)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Dinner.Title)
@Html.ValidationMessageFor(model => model.Dinner.Title)
</div>
</fieldset>
}
从通常的视图加载:
@model MyNerddiner.Models.DinnerFormViewModel
@{
ViewBag.Title = "Create";
}
<div id="Create" >
<h2>Host a Dinner</h2>
@Html.Partial("_DinnerForm")
</div>
控制器:
public ActionResult Create()
{
Dinner dinner = new Dinner()
{
EventDate = DateTime.Now.AddDays(7)
};
return View(new DinnerFormViewModel(dinner));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(DinnerFormViewModel dinnerViewModel)
{
Dinner dinner = null;
if (ModelState.IsValid)
{
try
{
dinner = dinnerViewModel.Dinner;
UpdateModel(dinner);
dinnerRepository.Add(dinner);
dinnerRepository.Save();
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
catch
{
ModelState.AddRuleViolations(dinner.GetRuleViolations());
return View(dinner);
}
}
return View(new DinnerFormViewModel(dinner));
}
现在,当我尝试创建(回发)时,出现错误:
没有为此对象定义无参数构造函数。
我可以猜测这是因为程序试图在某个地方启动DinnerFormViewModel
,但是在哪里,为什么以及如何使它正确?