Validate control inside Partial View using jQuery in ASP.Net MVC

smcdevelopments
 
on Nov 12, 2021 11:14 PM
Sample_194474.zip
514 Views

In my web application, there is a couple of partial views

From the Combo box selects the value, related partial views shown and other partial views stays as hidden.

I want to add client-side validation for each partial view. I tried adding validation to each partial view. But it won't work. So need help to solve this. Do I need to add validation on the main view for each partial view or am I doing something wrong in the partial view validations?

This is I did validation for one partial view.

<li style="padding-bottom:15px">
@using (Html.BeginCollectionItem("GeneralItmsList"))
    {
      @Html.HiddenFor(model => model.TempID)
      <div class="form-horizontal" id="quickForm" onsubmit="return validateForm()" name="maind">

       @Html.ValidationSummary(true, "", new { @class = "text-danger" })
       <div class="row">
         <div class="col-md-5 col-sm-6">
            <div class="form-group">
             Select Item Description
            <div class="col-md-10">
             @Html.EditorFor(model => model.Attachment_Description, new { htmlAttributes = new { @class = "form-control", @name = "description" } })
             @Html.ValidationMessageFor(model => model.Attachment_Description, "", new { @class = "text-danger" })

            </div>
           </div>
         </div>
         <div class="col-md-3 col-sm-6">
             <div class="form-group">
                Attachment Amount
              <div class="col-md-10">
                  <div class="input-group-prepend">
                  <span class="input-group-text">Rs.</span>
                  @Html.EditorFor(model => model.Attachment_Amount, new { htmlAttributes = new { @class = "form-control" } })
                  </div>
                  @Html.ValidationMessageFor(model => model.Attachment_Amount, "", new { @class = "text-danger" })
                  </div>
                </div>
               </div>

            <div class="col-md-3 col-sm-6">
              <div class="form-group">
                 Attachment
              <div class="col-md-10">
              <input type="file" name="ImageData@(Model.TempID.ToString())" id="ImageData@(Model.TempID.ToString())" multiple="multiple" data-id="Img@(Model.TempID.ToString())" onchange="checkImage(this)" />
                            @Html.ValidationMessageFor(model => model.Attachment, "", new { @class = "text-danger" })
                </div>
                @if (Model.Attachment != null)
                 {
                 <img src="data:image;base64,@System.Convert.ToBase64String(Model.Attachment)" width="100" height="100" class="ml-1"/>
                   }
                    </div>
                    <img id="Img@(Model.TempID.ToString())" src="" alt="" width="100" height="100" class="ml-1" />
                </div>
                <button type="button" class="btn btn-danger" onclick="$(this).parent().remove();">Remove</button>
            </div>
        </div>
    }
</li>
<script>
    function validateForm() {
        let x = document.["maind"]["description"].value;
        alert(x);
        if (x == "") {
            alert("Description must filled");
            return false;
        }
    }
</script>

So I checked this but it won't work. 

Here is my main index view. There you can see when user selects a value from the combo box, some partial views visible and others hides. So in this kind of situation where I  put validations? I also think we cannot validate every partial view from the index view. But when I try to put validation run on the partial view. It also not work. Can any one help me on this. Thank you.

This is the main view

<div class="col-md-6 col-sm-6">
   <div class="form-group row">
        @Html.LabelFor(model => model.ReqType, htmlAttributes: new { @class = "control-label col-md-3" })
        <div class="col-sm-8">
           @Html.DropDownListFor(model => model.ReqType, ReqTypes, "Select Request Type", new { @class = "js-dropdown" })
                                          
           @Html.ValidationMessageFor(model => model.ReqType, "", new { @class = "text-danger" })
         </div>
     </div>
 </div>
Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 15, 2021 04:30 AM
on Nov 19, 2021 12:18 AM

Hi smcdevelopmen...,

Check this example. Now please take its reference and correct your code.

Model

Customer

public class Customer
{
    [Key]
    public int Id { set; get; }
    [Required]
    public string Name { set; get; }
    [Required]
    public string Country { set; get; }
    public List<CourseModel> Courses { get; set; }
}

CustomerModel

public class CourseModel
{
    public int Id { get; set; }
    [Required]
    public string Course { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        Customer customer = new Customer();
        customer.Courses = GetCourses();
        return View(customer);
    }

    [HttpPost]
    public ActionResult Index(Customer model)
    {
        return View(model);
    }

    private static List<CourseModel> GetCourses()
    {
        List<CourseModel> courses = new List<CourseModel>();
        courses.Add(new CourseModel { Id = 1, Course = "ASP.Net" });
        courses.Add(new CourseModel { Id = 2, Course = "MVC" });
        courses.Add(new CourseModel { Id = 3, Course = ".Net Core" });
        courses.Add(new CourseModel { Id = 4, Course = "SQL" });
        return courses;
    }
}

View

Index

@model Customer
@using Validate_PartialView_MVC.Models;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        function validateForm() {
            $('.course').each(function () {
                var course = $(this).val();
                if (course == "") {
                    alert("Course must filled");
                }
            });
            return false;
        }
    </script>
</head>
<body>
    @using (Html.BeginForm())
    {
        if (Model.Courses != null)
        {
            foreach (CourseModel interest in Model.Courses)
            {
                Html.RenderPartial("CourseEditor", interest);
            }
        }
        <p>
            <input type="submit" value="Save" onclick="return validateForm()" />
        </p>
    }
</body>
</html>

PartialView

@model Validate_PartialView_MVC.Models.CourseModel

@using (Html.BeginCollectionItem("Courses"))
{
    @Html.HiddenFor(model => model.Id)
    <div name="maind">
        <div>
            @Html.LabelFor(model => model.Course)
            @Html.EditorFor(model => model.Course, new { htmlAttributes = new { @class = "form-control course" } })
        </div>
    </div>
}

Screenshot