如何在多个模型中验证单个模型
这是我的两个ModelA模型
public class ModelA
{
[Display(Name = "Test1")]
[Required(ErrorMessage = "Test1 is required.")]
public string Test1 { get; set; }
}
我的第二个模型ModelB
public class ModelB
{
[Display(Name = "Test2")]
[Required(ErrorMessage = "Test2 is required.")]
public string Test2 { get; set; }
}
我的主模型
public class MainModel
{
public ModelA ModelA { get; set; }
public ModelB ModelB { get; set; }
}
这是我的Index.cshtml
@using (Html.BeginForm("Test1", "SubmitModel", FormMethod.Post, new { id = "TestForm", role = "form", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.TextBoxFor(Model => Model.ModelA.Test1, new { @class = "form-control" })
@Html.ValidationMessageFor(Model => Model.ModelA.Test1, "", new { @class = "text-danger" })
@Html.TextBoxFor(Model => Model.ModelB.Test2, new { @class = "form-control" })
@Html.ValidationMessageFor(Model => Model.ModelB.Test2, "", new { @class = "text-danger" })
<input type="submit" value="next" />
}
我的控制器我的问题所在,我必须验证单个模型
public PartialViewResult Test1(MainModel model)
{
if (TryValidateModel(model.ModelA)) // This will validate both model at a time not a single model
{
return PartialView("Index", model);
}
return PartialView("Index");
}
如何仅验证一个模型,例如,如果Textbox Text one为空,则一次只能验证一个模型,这意味着在此阶段只能验证ModelA
发布于 2018-03-01 07:29:11
您可以尝试如下所示:
public PartialViewResult Test1(MainModel model)
{
if(string.IsNullOrWhiteSpace(Model.ModelB.Test1)
{
ModelState.Remove("Model.ModelB.Test2");
if (TryValidateModel(model.ModelA))
{
return PartialView("Index", model);
}
}
return PartialView("Index");
}
但是完全不清楚你为什么需要这样的东西。
发布于 2018-03-01 10:20:33
DefaultModelBinder将在进行绑定时为您验证所有内容。如果MainModel对象的所有条件都正常,则设置ModelState.IsValid。
public PartialViewResult Test1(MainModel model)
{
if (ModelState.IsValid)
{
return PartialView("Index", model);
}
return PartialView("Index");
}
https://stackoverflow.com/questions/49044234
复制