【发布时间】:2020-01-19 13:44:03
【问题描述】:
我一直在努力处理 asp.net 中的模型验证消息
我有一个视图模型使用的模型。 如果用户未填写必填字段,我希望我的视图显示验证错误。
当未填写必填字段(预期行为)但我看不到时,我的 ModelState.IsValid 为 false 任何错误信息
我的模型类:
public class Model
{
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
[Required(ErrorMessage = "Adress is required.")]
public string Adress { get; set; }
}
我的 ViewModel 类:
public class ViewModel
{
[Required]
public Model SelectedModel { get; set; }
public string Title { get; set;}
}
我的控制器:
[HttpPost]
public ActionResult Create(ViewModel vm)
{
try
{
if (ModelState.IsValid)
{
bool result = *DatabaseStuff*
if(result == true)
{
return RedirectToAction("Index");
}
else
{
return View();
}
}
return RedirectToAction("Index",vm);
}
catch
{
return View();
}
}
我的观点
@model ViewModel
@using (Html.BeginForm("Create", "MyController", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="box box-primary">
<div class="box-header with-border">
<h4 class="box-title">ViewModel Form</h4>
</div>
<div class="box-body">
<div class="row">
<div class="col-md-12">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.SelectedModel.Name, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.SelectedModel.Name, null, "SelectedModel_Name",new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SelectedModel.Name, "", new { @class = "text-danger", @data_valmsg_for = "SelectedModel_Name" })
</div>
<div class="form-group">
@Html.LabelFor(model => model.SelectedModel.Adress, htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.SelectedModel.Adress, null, "SelectedModel_Adress",new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.SelectedModel.Adress, "", new { @class = "text-danger", @data_valmsg_for = "SelectedModel_Adress" })
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="box-footer">
<input type="submit" value="Create" class="btn btn-success pull-right" />
</div>
</div>
</div>
}
谢谢。
【问题讨论】:
-
我认为你不应该使用 RedirectToAction 而只返回当前模型的视图。喜欢你的收获。
-
而且我认为模型验证默认不嵌套。它仅适用于第一个视图模型。
-
RedirectToAction 不会改变任何东西,因为我将它用于其他模型,并且在需要时显示验证消息。当名称或地址字段 ModelState.IsValid == false 时,ModelValidation 工作正常。我们可以观察 ModelStateDictionnary ,它实际上包含错误。
-
@daremachine 关于返回视图,您是对的。但奇怪的是,redirectToAction 显示模型的验证消息而不是视图模型中的模型
标签: c# asp.net-mvc