[英]MVC 5 Razor handling view when validation fails
I have an MVC Razor layout with a WebGrid. 我有一个带有WebGrid的MVC Razor布局。
@Html.ValidationSummary()
<div>
@model List<DelsDTO>
@{
var grid = new WebGrid(Model, defaultSort: "Name");
}
@grid.GetHtml(headerStyle: "webgrid-header", columns: grid.Columns(
grid.Column(header: "Select", format: @<text><input name="checkedDelUnits" type="checkbox" value="@item.delId" /></text>),
grid.Column("DelId", header: "ID"),
grid.Column("Name", style: "nameColLen"),
grid.Column("CRate", header: "C Rate", style: "span1", format: (item) =>
(item.CRate == null) ? String.Empty : String.Format("{0:0.00}", @item.CRate))
)
)
<td><input type="submit" name="saveChanges" value="Save Changes" /></td>
}
</div>
Using a submit button I perform validation checks in a controller method. 使用提交按钮,我在控制器方法中执行验证检查。 If the validation fails I set: 如果验证失败,我设置:
ModelState.AddModelError("", "No records Selected");
return View("Search");
At this point I have no datasource for the view so it is returned with an empty grid. 此时,我没有该视图的数据源,因此它以空网格返回。 What is best practice for handling this? 处理此问题的最佳实践是什么?
Should I pass the webgrid datasource (model) from the view to the controller only to pass it back if validation fails? 是否应该将Webgrid数据源(模型)从视图传递到控制器,以便仅在验证失败时将其传递回控制器? If so how do that? 如果是这样,那该怎么办?
If the validation fails you basically need to create the model once again since it is not saved anywhere. 如果验证失败,则基本上需要再次创建模型,因为它不会保存在任何地方。 So if on the initial action you were doing something like (just an idea below): 因此,如果在最初的操作中您正在做类似的事情(只是以下想法):
var model = GetGridModel();
return View("Search", model);
You would need to do the same on submit when validation failed: 验证失败时,您需要对提交执行相同的操作:
ModelState.AddModelError("", "No records Selected");
var model = GetGridModel();
return View("Search", model);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.