How can the check sub-model state is valid or not instead of checking the main model state in asp.net core?

Viewed 150

Models : Here SubjectDetailsModel contain sub-model StudentDetailsModel

    public class SubjectDetailsModel
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string SubjectName { get; set; }
        [Required]
        public string SubjectCode { get; set; }

        public StudentDetails studentDetails { get; set; }

    }

    public class StudentDetailsModel
    {
        [Key]
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        public string EnrollmentNumber { get; set; }
        [Required]
        public string Gender { get; set; }
        [Required]
        public string City { get; set; }

    }

Controller

Let me know when I'm passing the SubjectDetailsModel as a Parameter in the post method of Index and this time I need to check only the StudentDetailsModel state is valid or not. So how can I do it?

    public class HomeController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Index(SubjectDetailsModel model)
        {
            //Here i need to check StudentDetails ModelState.Isvalide instead of SubjectDetails model. OR
            //How can the check sub-model state is valid or not instead of checking the main model state?
            if (ModelState.IsValid) // This condition checking SubjectDetailsModel State.
            {
                // Insert recorde
            }
            return View(model);
        }
    }

View

@model SubjectDetailsModel
<form method="post" asp-action="Index" asp-controller="Home">
    <input asp-for="Id" hidden />
    <input asp-for="SubjectName"/>
    <input asp-for="SubjectCode" />
    <input asp-for="studentDetails.Name"/>
    <input asp-for="studentDetails.Gender" />
    <input asp-for="studentDetails.City" />
    <button type="submit">Submit</button>
</form>
1 Answers

If you need to put validation attributes on the mail model as well, that might a bit tricky. For your case, I would recommend using Fluent Validation NuGet package, which will help write your custom validation code, in a separate class.

If would look like this:

    public class SubjectDetailsModelValidator : AbstractValidator<SubjectDetailsModel>
    {
        public SubjectDetailsModelValidator()
        {
            RuleFor(x => x.studentDetails.Name).NotEmpty();
            RuleFor(x => x.studentDetails.EnrollmentNumber).NotEmpty();
            RuleFor(x => x.studentDetails.Gender).NotEmpty();
            RuleFor(x => x.studentDetails.City).NotEmpty();
        }
    }

Here are the docs, take a look: https://docs.fluentvalidation.net/en/latest/aspnet.html

Related