How can i validate single model in multiple model
Here are my two Model ModelA
public class ModelA
{
[Display(Name = "Test1")]
[Required(ErrorMessage = "Test1 is required.")]
public string Test1 { get; set; }
}
My Second Model 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
@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
TryValidateModel()is not even really necessary. TheDefaultModelBinderhas already validated theMainModeland added errors toModelStatefor bothModelAandModelB