[英]MVC How to use View Model pattern when view has more fields than needed to save data
我的MVC页面用于插入和更新。 到目前为止,它可以很好地显示数据,但是当单击“提交”按钮时,它会出错:
"No parameterless constructor defined for this object."
MissingMethodException: No parameterless constructor defined for this object.]
它将击中无参数构造函数,现在被注释掉。 viwemodel上有50个额外字段,这些字段仅用于显示,在插入/更新中不需要。 表单上的表单字段少于视图模型中的表单字段。
是否有可以处理这种情况的工作代码示例? 我在这里看到了可能有效的答案,但是由于我是新手,因此我需要一个完整的工作示例:
<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);
}
错误消息非常清楚: 模型类中需要无参数的构造函数 。
因此,您需要在IncidentViewModel类中添加另一个不带参数的构造函数,或者从现有的构造函数中删除该参数。
我认为您必须从ViewModel中删除构造函数。我认为ViewModels与数据方法和构造函数无关。控制器负责此类职责,您可以在controller动作中简单地将其替换为类似的东西:
IncidentViewModel vwIncidentData = new IncidentViewModel();
if(objIncidentBO.objIncident.IncidentModel.IncidentId !=0)
{
vwIncidentData.IncidentId = objIncidentBO.objIncident.IncidentModel.IncidentId;
vwIncidentData.objIncident = IncidentModelBO.Get(incidentId);
}
无论如何,此行可能会导致您执行错误,因此请检查并确保它不为null:
objIncidentBO.objIncident.IncidentModel.IncidentId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.