我的MVC頁面用於插入和更新。到目前爲止,它工作正常顯示的數據,但點擊提交按鈕時,錯誤:MVC如何查看模型模式,當視圖的字段多於保存數據所需的字段時
"No parameterless constructor defined for this object."
MissingMethodException: No parameterless constructor defined for this object.]
它將擊中paramaterless構造,它現在被註釋掉了。 viwemodel上有50個額外的域,僅用於顯示,不需要插入/更新。窗體中的表單字段少於視圖模型中的表單字段。
有處理這種情況的工作代碼示例嗎? 我看到這裏接受的答案,可能工作,但我需要一個完整的工作的例子,因爲我是新來做到這一點:
ASP.NET MVC - Proper usage of View Model and Command pattern
<form action="/incident/SaveIncident" method="post">
<div>
<input class="btn btn-primary" type="submit" value="SubmitSave" />
<br />
<select id="drpSite">
<option value="0">Pick a site...</option>
@foreach (var site in Model.Sites)
{
<option value="@site.SiteId">
@site.SiteName
</option>
}
</select>
<br />
upsert:@Html.TextBoxFor(model => model.objIncidentUpsert.UpsertBemsId, new { @class = "form-control" })
<br />
viewBOIncDesc1: @Html.TextBoxFor(model => Model.objIncident.IncidentModel.IncidentDescription1, new { @class = "form-control" }))
</div>
</form>
IncidentViewModel.cs
public class IncidentViewModel
{
public int IncidentId { get; set; }
public IncidentModelBO objIncident { get; set; }
public IncidentModelUpsert objIncidentUpsert { get; set; }
public IncidentViewModel(int incidentId)
{
if (incidentId == 0)
{
objIncident = new IncidentModelBO();
}
else
{
IncidentId = incidentId;
objIncident = IncidentModelBO.Get(incidentId);
}
}
public IEnumerable<SiteModel> Sites {get; set;}
}
IncidentController.cs:
//[HttpPost]
//[ActionName("SaveIncident")]
//public ActionResult SaveIncident()
//{
// return new HttpStatusCodeResult(400, "Problem with inputxxx ");
//}
[HttpPost]
[ActionName("SaveIncident")]
public ActionResult SaveIncident(IncidentViewModel objIncidentBO)
{
string loggedinbemsid = System.Web.HttpContext.Current.Session[Utility.SessionKeyIndex.BEMSID.ToString()].ToString();
try
{
objIncidentBO.objIncident.Create(loggedinbemsid, null);
IncidentViewModel vwIncidentData = new IncidentViewModel(objIncidentBO.objIncident.IncidentModel.IncidentId);
return View("index", vwIncidentData);
}
catch (Exception e)
{
return new HttpStatusCodeResult(400, "Problem with input: " + e.Message);
}
正如羅伯特的回答狀態,你必須有一個無參數的構造函數,因爲'DefaultModelBinder '使用'Activator.CreateInstance()'初始化你的模型,如果你沒有的話會拋出異常。但是,儘管你的模型的名稱,它不是MVC上下文中的視圖模型。視圖模型不應包含數據模型,也不應包含數據庫訪問代碼。建議您閱讀[MVC中的ViewModel是什麼?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –
非常感謝您解釋我錯過了什麼。我有很多要學習的。 – Remy