Asp.net mvc 复杂模型上的ASP.NET MVC验证
我在验证视图上的表单时遇到困难 我有一个控制器,它执行Asp.net mvc 复杂模型上的ASP.NET MVC验证,asp.net-mvc,Asp.net Mvc,我在验证视图上的表单时遇到困难 我有一个控制器,它执行UpdateModel(对象),因此不确定如何构建验证 我已为所有强制属性添加了[必需(ErrorMessage=“请输入联系人姓名”)] 我怎样才能让一切顺利?因为我的控制器正在做一些复杂的事情。以下是控制器代码: [HttpPost] public ActionResult PersistListing() { var listingView = new MaintainListingVie
UpdateModel(对象)代码>,因此不确定如何构建验证
我已为所有强制属性添加了[必需(ErrorMessage=“请输入联系人姓名”)]
我怎样才能让一切顺利?因为我的控制器正在做一些复杂的事情。以下是控制器代码:
[HttpPost]
public ActionResult PersistListing()
{
var listingView = new MaintainListingView();
if (!string.IsNullOrEmpty(Request["Listing.Guid"]))
{
var dbListing = _service.GetByGuid<Listing>(Guid.Parse(Request["Listing.Guid"]));
if (dbListing != null)
{
listingView.Listing = dbListing;
}
}
UpdateModel(listingView);
RebindTranslationsDictionary(listingView.Listing);
listingView.Listing.CategoryId = _service.GetByGuid<ListingCategory>(listingView.SelectedListingCategoryGuid).Id;
_service.PersistEntity(listingView.Listing);
return RedirectToAction("Edit", new { id = listingView.Listing.Guid });
}
我的视图中是否需要EditForModel标记?您可以使用TryUpdateModel
而不是UpdateModel
,因为它不会引发异常,并允许您知道验证是否失败:
if (!TryUpdateModel(listingView))
{
// there were validation errors => redisplay the view
// so that the user can fix those errors
return View(listingView);
}
// at this stage you know that validation has passed
// and you could process the model ...
你能给我们看看你的模型吗?你得到的确切错误是什么?但我想让错误信息显示出来。我正在使用Html.TextBoxFor()创建控件。然后添加相应的Html.ValidationMessageFor(x=>x.SomeProperty)
helper。或者使用Html.ValidationSummary()
显示所有错误消息。确定。。。因为我的视图是强类型的,如果TryUpdateModel失败,我如何在打开错误消息的情况下将用户重定向到同一视图?您只需返回视图并将视图模型传递给它:返回视图(listingView)代码>。ASP.NET MVC中没有打开的错误消息
。如果您已将ValidationMessageFor helpers放置在此视图中,并且ModelState中存在错误,则将显示这些错误。当从请求值执行模型绑定时,TryUpdateModel方法将这些错误消息添加到ModelState。我已经在电话输入控件上添加了ValidationMessageFor,但它没有显示错误消息:@Html.ValidationMessageFor(m=>m.Listing.TelephoneNumber)@Html.TextBoxFor(m=>m.Listing.TelephoneNumber)
if (!TryUpdateModel(listingView))
{
// there were validation errors => redisplay the view
// so that the user can fix those errors
return View(listingView);
}
// at this stage you know that validation has passed
// and you could process the model ...