我想了解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));
}
現在,當我試圖創建(上回發),我得到一個錯誤:
No parameterless constructor defined for this object.
我可以猜到,這是因爲某個程序試圖啓動DinnerFormViewModel
,但在那裏,爲什麼?我應該怎樣做纔對?
謝謝,但即使在創建DinnerFormViewModel的另一個無參數構造函數後,我也得到了相同的錯誤。現在它發生在linq生成的類中。 – happyZZR1400 2012-07-17 19:52:02
順便問一下:爲什麼創建一個空實例來填充請求中的數據,當實例已經在第一個路由中創建時? – happyZZR1400 2012-07-17 19:54:59
僅當路由在請求中找到與預期的方法參數匹配的模式時才創建實例。 – Maess 2012-07-17 20:05:02