ASP.Net MVC: Restrict submit form without selecting ComboBox in PartialView

smcdevelopments
 
on Jun 29, 2022 12:10 AM
567 Views

In my ASP.NET MVC project, create view consist of a main view and another couple of partial views.

So in one partial view, there is a combo box, I want to restrict it without selecting a value, so the user cannot submit the form.

I tried writing a JavaScript within that partial view, but it won't work. So want to know if there are any other ways to do this restriction?

 <div class="form-group row">
     @Html.Label("Select the Approver", htmlAttributes: new { @class = "control-label col-md-3" })
      <div class="col-sm-8">
       @Html.DropDownListFor(model => model.Approver_Id, new List<SelectListItem>(), new { @id = "ddlEmployees", @class = "js-dropdown" })
        @Html.ValidationMessageFor(model => model.Approver_Id, "", new { @class = "text-danger" })
  </div>
</div>

I can't use it on the model as required because some options in this combo box get hidden before submitting the form. So If I apply required to the model, the form does not get submitted for those options also.

Any suggestions would help me. :)

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jul 01, 2022 05:30 AM
on Jul 02, 2022 04:07 AM

Hi smcdevelopmen...,

Use jQuery to validate the partial view controls.

Assign jQuery Click event handler to the submit button.

The check the DropDownList selected value, if invalid show the message.

Refer below example.

Model

public class CustomerModel
{
    [Required(ErrorMessage = "Id Required!")]
    public string CustomerID { get; set; }

    [Required(ErrorMessage = "Name Required!")]
    public string Name { get; set; }

    public string City { get; set; }

    public int Gender { get; set; }
}

Controller

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(CustomerModel customer)
    {
        return View();
    }
}

View

@model PartialView_Action_MVC.Models.CustomerModel

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <style type="text/css">
        body { font-family: Arial; font-size: 10pt; }
        table { border: 1px solid #ccc; border-collapse: collapse; background-color: #fff; }
        table th { background-color: #B8DBFD; color: #333; font-weight: bold; }
        table th, table td { padding: 5px; border: 1px solid #ccc; }
        table, table table td { border: 0px solid #ccc; }
        table td { vertical-align: top; }
        .error { color: red; }
        select { width: 175px; }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table cellpadding="0" cellspacing="0">
            <tr>
                <th colspan="2" align="center">Person Details</th>
            </tr>
            <tr>
                <td>CustomerID: </td>
                <td>
                    @Html.TextBoxFor(m => m.CustomerID)
                    @Html.ValidationMessageFor(m => m.CustomerID, "", new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td>Name: </td>
                <td>
                    @Html.TextBoxFor(m => m.Name)
                    @Html.ValidationMessageFor(m => m.Name, "", new { @class = "error" })
                </td>
            </tr>
            <tr>
                <td>Gender: </td>
                <td>
                    @{ Html.RenderPartial("Details", Model); }
                </td>
            </tr>
            <tr>
                <td>City: </td>
                <td>
                    @Html.TextBoxFor(m => m.City)
                </td>
            </tr>
            <tr>
                <td></td>
                <td><input type="submit" value="Submit" /></td>
            </tr>
        </table>
    }
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.js"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.12/jquery.validate.unobtrusive.js"></script>
    <script type="text/javascript">
        $(function () {
            $('[id*=btnSubmit]').click(function () {
                var gender = $("#ddlGender").val();
                if (gender == "") {
                    alert("Gender required.");
                    return false;
                }
            });
        });
    </script>
</body>
</html>

PartialView

@model PartialView_Action_MVC.Models.CustomerModel
@Html.DropDownListFor(model => model.Gender, new List<SelectListItem>
                   { new SelectListItem{Text="Male", Value="1"},
                     new SelectListItem{Text="Female", Value="2"}}, "Please select", new { @id = "ddlGender" })
@Html.ValidationMessageFor(model => model.Gender, "", new { @class = "error" })

Screenshot