我的MVC页面用于插入和更新。到目前为止,它适用于显示数据,但是当单击提交按钮时,它会出错:
"No parameterless constructor defined for this object."
MissingMethodException: No parameterless constructor defined for this object.]
它将击中无表情的构造函数,它现在被注释掉了。 viwemodel上有50个额外字段,仅用于显示,在插入/更新时不需要。表单上的表单字段少于viewmodel中的表单字段。
是否有处理这种情况的工作代码示例? 我已经看到这里可以接受的答案,但是我需要一个完整的工作示例,因为我是新手来做这个:
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);
}
答案 0 :(得分:3)
错误信息非常明确:您需要在模型类中使用无参数构造函数。
因此,您需要在 IncidentViewModel 类中添加另一个没有参数的构造函数,或者您需要从现有参数中删除该参数。
答案 1 :(得分:2)
我认为你必须从ViewModel中删除构造函数。我认为viewmodels与数据方法和构造函数无关。控制器负责这样的职责,你可以简单地在控制器动作中用这样的东西替换构造函数:
IncidentViewModel vwIncidentData = new IncidentViewModel();
if(objIncidentBO.objIncident.IncidentModel.IncidentId !=0)
{
vwIncidentData.IncidentId = objIncidentBO.objIncident.IncidentModel.IncidentId;
vwIncidentData.objIncident = IncidentModelBO.Get(incidentId);
}
无论如何,这一行可能会导致执行错误问题,所以检查它并确保它不为空:
objIncidentBO.objIncident.IncidentModel.IncidentId