简体   繁体   English

在多模型 ASP.NET MVC 中验证单个模型

[英]Validate single Model in Multiple Model ASP.NET MVC

How can i validate single model in multiple model如何在多个模型中验证单个模型

Here are my two Model ModelA这是我的两个模型 ModelA

public class ModelA
{
    [Display(Name = "Test1")]
    [Required(ErrorMessage = "Test1 is required.")]
    public string Test1 { get; set; }
}

My Second Model ModelB我的第二个模型 ModelB

public class ModelB
{
    [Display(Name = "Test2")]
    [Required(ErrorMessage = "Test2 is required.")]
    public string Test2 { get; set; }
}

My Main Model我的主要模型

public class MainModel
{
    public ModelA ModelA { get; set; }
    public ModelB ModelB { get; set; }
}

Here is my Index.cshtml这是我的 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" />
}

My Controller where my problem exists I have to validate a single model我的控制器存在我的问题 我必须验证一个模型

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");
}

How can i validate only one model For eg if Textbox Text one is empty i have to validate only one model at a time means ModelA at this stage我如何只验证一个模型 例如,如果文本框文本一个为空,我一次只能验证一个模型,这意味着在此阶段 ModelA

You can try something like below:您可以尝试以下操作:

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");
}

But it is totally unclear why you would need something like this.但是完全不清楚为什么你需要这样的东西。

The DefaultModelBinder will validate all for you when it make the bind. DefaultModelBinder 将在进行绑定时为您验证所有内容。 ModelState.IsValid set if all conditions are OK at MainModel objects.如果 MainModel 对象的所有条件都正常,则设置 ModelState.IsValid 。

public PartialViewResult Test1(MainModel model)
{
    if (ModelState.IsValid)  
    {
        return PartialView("Index", model);
    }
    return PartialView("Index");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM