Parshuram Kalvikatte
Parshuram Kalvikatte

Reputation: 1636

Validate single Model in Multiple Model ASP.NET MVC

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

Upvotes: 1

Views: 1334

Answers (2)

Jordi Jordi
Jordi Jordi

Reputation: 481

The DefaultModelBinder will validate all for you when it make the bind. ModelState.IsValid set if all conditions are OK at MainModel objects.

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

Upvotes: 0

Adnan Niloy
Adnan Niloy

Reputation: 469

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.

Upvotes: 1

Related Questions