取消选中CheckBox时,ModelState验证失败

时间:2015-12-01 07:23:38

标签: asp.net-mvc asp.net-mvc-4 checkbox

在视图中:

@model  MvcDNC.Models.clsDSAMaster
@{

    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "wfrmDSAMaster";

    var grid = new WebGrid( Model.DSAList,canPage: true, canSort: false, rowsPerPage: 10);
    int rowVal = 0;
}
<head>
<script language="javascript" type="text/javascript">
    window.history.forward(1);
    function NumbersOnly() {
        //alert(event.keyCode);
        if (((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) && event.keyCode != 8) {
            alert("Enter Numbers only");
            return false;
        }
        else {
            return true;
        }
    }
    $(document).ready(function () {
        if ('@ViewBag.flag' == 'edit') {
            $("#tblfooterbtn").css('display', 'none');
            $("#tblDSADisp").css('display', 'none');
            $("#pnlNewDSA").css('display', 'block');
            $("#update").css('display', 'block');
            $("#save").css('display', 'none');

        }
        var count = 0;

        $("#btnSearch").click(function () {
            var text = $("#ddlFieldName option:selected").text();
            $("#ddlFieldName option:selected").val(text);
        });

        $("#btnAddDSA").click(function () {

            $("#tblfooterbtn").css('display', 'none');
            $("#tblDSADisp").css('display', 'none');
            $("#pnlNewDSA").css('display', 'block');
            $(':input', '#form0').removeAttr('selected').not(':button, :submit, :reset, :hidden').val('');
            $('#Insert_DSA_ChkFlag').prop('checked', true);
        });

        $("#btnCancel").click(function () {

            $("#tblfooterbtn").css('display', 'block');
            $("#tblDSADisp").css('display', 'block');
            $("#pnlNewDSA").css('display', 'none');
        });

        $("#btnSubmit").click(function () {
            //            $("#tblfooterbtn").css('display', 'block');
            //            $("#tblDSADisp").css('display', 'block');
            //            $("#pnlNewDSA").css('display', 'none');
            validateBANID();

        });

        $("#btnUpdate").click(function () {
            $("#tblfooterbtn").css('display', 'block');
            $("#tblDSADisp").css('display', 'block');
            $("#pnlNewDSA").css('display', 'none');

        });

        $(".btnEdit").click(function () {
            var _strDSAID = ($(this).parent().siblings(':first').next()).html();

            window.location.href = "/DSA/GetDSADetails?id=" + _strDSAID;

        });

        $(".btnChangeStatus").click(function () {
            var changeStatus = $(this);
            var edit = $(this).prev();
            changeStatus.prop("disabled", true);
            edit.prop("disabled", true);
            var _strDSAID = ($(this).parent().siblings(':first').next()).html();
            var _strStatus = ($(this).parent().siblings(':first').next().next().next().next()).text();

            $.post("UpdateDSAStatus", { id: _strDSAID, Status: _strStatus }, function (data, changeStatus, edit) {
                $("#lblError").html(data);
            });

        });

        $("#Insert_DSA_CountryCode").change(function () {
            var country = this.value;

            $.post("GetLocations", { Location: country, Type: "country" }, function (data) {

                $("#Insert_DSA_StateCode").html(data);


            });
        });

        $("#Insert_DSA_StateCode").change(function () {
            var state = this.value;
            $.post("GetLocations", { Location: state, Type: "state" }, function (data) {
                $("#Insert_DSA_CityCode").html(data);

            });
        });
        $("body").on('click', '.btnAddMore', function () {
            var parent = $(this).parent();
            $(this).remove();
            parent.after('<div class="row" style="left:-5px;position:relative;text-align:left; width:80%"><div class="col-xs-6 col-sm-6 col-md-6 col-lg-6"></div><div class="col-xs-3 col-sm-3 col-md-3 col-lg-3"><input type="text"/></div><button class= "btnAddMore" style="left:0px;position:relative;">Add More</button></div>');
        });


        $("#Insert_DSA_RSMId").blur(function () {
            var id = this.value;
            $.post("GetSM_ASM_RSM", { id: id, Type: "RSM" }, function (data) {
                data = data.toString();
                var result = data.split(',');
                $("#Insert_DSA_RSMName").val(result[0]);
                $("#hdnRsmID").val(result[1]);
                $("#Insert_DSA_RSMEmail").val(result[2]);

            });
        });

        $("#Insert_DSA_ASMId").blur(function () {
            var id = this.value;
            $.post("GetSM_ASM_RSM", { id: id, Type: "ASM" }, function (data) {
                data = data.toString();
                var result = data.split(',');
                $("#Insert_DSA_ASMName").val(result[0]);
                $("#hdnASmID").val(result[1]);
                $("#Insert_DSA_ASMEmail").val(result[2]);

            });

        });

        $("#Insert_DSA_SMId").blur(function () {
            var id = this.value;
            $.post("GetSM_ASM_RSM", { id: id, Type: "SM" }, function (data) {
                data = data.toString();
                var result = data.split(',');
                $("#Insert_DSA_SMName").val(result[0]);
                $("#hdnSmID").val(result[1]);
                $("#Insert_DSA_SMEmail").val(result[2]);

            });

        });


    });
    function OnSuccess(data) {

        $("#lblError").html(data);
    }

    function OnFailure(response) {
//        alert("There was an error in adding DSA");
    }
    function validateBANID()
    {
        var vRSM = document.getElementById('Insert_DSA_RSMId').value;
        var vASM = document.getElementById('Insert_DSA_ASMId').value;
        var vSM = document.getElementById('Insert_DSA_SMId').value;
        if (vRSM == '' && vASM == '' && vSM == '') {
            alert('Two out of these three are compulsory');
            return false;
        }
        else if (vRSM != '' && vASM == '' && vSM == '') {
            alert('Two out of these three are compulsory');
            return false;
        }
        else if (vRSM == '' && vASM != '' && vSM == '') {
            alert('Two out of these three are compulsory');
            return false;
        }
        else if (vRSM == '' && vASM == '' && vSM != '') {
            alert('Two out of these three are compulsory');
            return false;
        }
        return true;
    }
</script>
</head>
<center>

<div class="container" id="tblDSADisp">
    <div class="header3">
            <center>@Html.Label("lblHeading", "DSA Master") </center> 
    </div><br />
    @using (Html.BeginForm("wfrmDSAMaster", "DSA", FormMethod.Post, new { id = "DSAMaster" }))
    {
    <div class="row">
            <div class="col-md-2 col-sm-2">
               @Html.Label("lblFieldName", "Field Name :")
            </div>
            <div class="col-md-2 col-sm-2">
                @Html.DropDownList("ddlFieldName", new List<SelectListItem>
                {
                                                new SelectListItem{ Text="DSA ID", Value = "DDM_DSAID" ,Selected=true}, 
                                                new SelectListItem{ Text="DSA NAME", Value = "DDM_DSANAME" },
                                                new SelectListItem{ Text="COMPANY", Value = "DDM_COMPANYNAME" },
                                                new SelectListItem{ Text="WORKPHONE", Value = "DDM_WORKPHONE" },
                                                new SelectListItem{ Text="OUTBOUND NO", Value = "DDP_PHONENO" }
                })
            </div>
            <div class="col-md-1 col-sm-1">
                @Html.Label("lblKeyword", "Keyword:")
             </div>  
            <div class="col-md-2 col-sm-2">
                @Html.TextBox("txtkeyword", "")
                @Html.DropDownList("ddlRoleNames", Enumerable.Empty<SelectListItem>(), new { @class = "hidden" })
            </div>
            <div class="col-md-1 col-sm-1">
                @Html.Label("lblCriteria", "Criteria :")
            </div>
            <div class="col-md-2 col-sm-2">
                @Html.DropDownList("ddlCriteria", new List<SelectListItem>
                {
                                            new SelectListItem{ Text="Exact Match", Value = "Exact_Match" ,Selected=true} ,
                                            new SelectListItem{ Text="Any", Value = "Any" } 
                })
            </div>
           <div class="col-md-1 col-sm-1">
                <input type="submit" id="btnSearch" runat="server" class="button" value="Search" name="command" text="Search"/>   
            </div>

    </div>   
    }
    <div class="row">
          <div class="col-md-3 col-sm-3">
          </div>
          <div class="col-md-6 col-sm-6">
          <label id="lblSearchError" style = "color:Red" ></label>
        </div>
    </div>   

    <div class="row">
       @if (Model.DSAList.Count != 0)
       {
         @grid.GetHtml(tableStyle: "webGrid",
                    headerStyle: "header3",
                    footerStyle: "header3",
                    alternatingRowStyle: "alt",
                    selectedRowStyle: "select",
                                                   columns: grid.Columns(
                                          grid.Column("Sr.No.", format: item => rowVal = rowVal + 1),
                                          grid.Column("DSAID", "DSA ID"),
                                          grid.Column("DSANAME", "DSA Name"),
                                          grid.Column("COMPANYNAME", "Company"),
                                          grid.Column("STATUS", format: (item) =>
                                          {
                                              if (item.STATUS == "1")
                                              {
                                                  return Html.Raw(string.Format("<text>Active</text>"));
                                              }
                                              else
                                              {
                                                  return Html.Raw(string.Format("<text>Inactive</text>"));
                                              }
                                          }




                                          ),
                                          grid.Column("", format: (item) =>
                                          {
                                              if (item.locked == "Y")
                                              {


                                                  return Html.Raw(string.Format("<button class='btnEdit' style='width:50px' disabled>Edit</button>&nbsp; <button class='btnChangeStatus' disabled>Change Status</button>&nbsp;"));
                                              }
                                              else 
                                              {
                                                  return Html.Raw(string.Format("<button class='btnEdit' style='width:50px'>Edit</button>&nbsp; <button class='btnChangeStatus' >Change Status</button>&nbsp;"));
                                              }
                                          }


                        )))
       }
       @if (Model.DSAList.Count == 0)
       {
        @Html.Label("lblhstry", "NO RECORD EXISTS", new { style = "Font-Size:Small" })
       }
    </div>
    <div class="row" style="display:none">
         <input id="hdnSearchFlag" runat="server" name="hdnSearchFlag" type="hidden" visible="false" /> 
    </div>
</div>   

<div class="container" id="tblfooterbtn" >
        <button ID="btnAddDSA" runat="server"  class = "button">Add DSA</button><br/><br/>
</div>
<div class="row">
    <label id="lblError" style = "Width:100%; font-weight:bold; color:red"></label>
</div> 
<div class="container rowcolor1" id="pnlNewDSA" style="border:1px solid;width:60%;display:none" >
@using (Ajax.BeginForm("Save","DSA",
    new AjaxOptions { OnSuccess = "OnSuccess", OnFailure = "OnFailure" }))
{
    <div class="header3"  style="left:-15px;position:relative;width:105%">
            <center>@Html.Label("LblHeader", "DSA Details") </center> 
    </div><br />

    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblDSAID", "DSA ID")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
        @Html.TextBoxFor(m => m.Insert_DSA.DSAId, new { @maxlength = "10" })
        @Html.ValidationMessageFor(m => m.Insert_DSA.DSAId)
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblDSANAME", "DSA NAME")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
          @*@Html.TextBox("txtDSANAME", "", new { style = "AutoCompleteType:disabled; MaxLength:100" })*@
          @Html.TextBoxFor(m => m.Insert_DSA.Firstname, new { @maxlength = "100" })
           @Html.ValidationMessageFor(m => m.Insert_DSA.Firstname)
          </div>
    </div>
     <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblDSACMPNY", "DSA COMPANY")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
          @*@Html.TextBox("txtDSANAME", "", new { style = "AutoCompleteType:disabled; MaxLength:100" })*@
          @Html.TextBoxFor(m => m.Insert_DSA.Company, new { @maxlength = "70" })
          @Html.ValidationMessageFor(m => m.Insert_DSA.Company)
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblEMAILID", "EMAIL ID")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
          @*@Html.TextBox("txtEMAILID", "", new { style = "AutoCompleteType:disabled; MaxLength:70" })*@
           @Html.TextBoxFor(m => m.Insert_DSA.Email_Off, new { @maxlength=70 })
           @Html.ValidationMessageFor(m => m.Insert_DSA.Email_Off)
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblADDRESS1", "ADDRESS1")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
           @Html.TextBoxFor(m => m.Insert_DSA.Address1, new {@maxlength=45 })
           @Html.ValidationMessageFor(m => m.Insert_DSA.Address1)
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblADDRESS2", "ADDRESS2")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
          @*@Html.TextBox("txtADDRESS2", "", new { style = "AutoCompleteType:disabled; MaxLength:45" })*@
           @Html.TextBoxFor(m => m.Insert_DSA.Address2, new { @maxlength = 45 })
           @Html.ValidationMessageFor(m => m.Insert_DSA.Address2)
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblADDRESS3", "ADDRESS3")
        </div>
        <div class="col-md-6 col-sm-6">
          @*@Html.TextBox("txtADDRESS3", "", new { style = "AutoCompleteType:disabled; MaxLength:45" })*@
          @Html.TextBoxFor(m => m.Insert_DSA.Address3, new { @maxlength = 45 })
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblPIN", "PIN")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
          @*@Html.TextBox("txtPin", "", new { style = "AutoCompleteType:disabled; MaxLength:6" })*@
          @Html.TextBoxFor(m => m.Insert_DSA.PinCode, new { @maxlength = 6 })
          @Html.ValidationMessageFor(m => m.Insert_DSA.PinCode)
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblCOUNTRY", "COUNTRY")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
          @*@Html.DropDownList("ddlCountry", Model.lstCountry, new { style = "width:150px" })*@
          @Html.DropDownListFor(m => m.Insert_DSA.CountryCode, Model.lstCountry, new { style = "width:150px" })
          @Html.ValidationMessageFor(m => m.Insert_DSA.CountryCode)
         </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblSTATE", "STATE")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
          @*@Html.DropDownList("ddlState", Model.lstState, new { style = "width:150px" })*@
           @Html.DropDownListFor(m => m.Insert_DSA.StateCode, Model.lstState, new { style = "width:150px" })
           @Html.ValidationMessageFor(m => m.Insert_DSA.StateCode)
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblCity", "CITY")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
         @* @Html.DropDownList("ddlCity", Model.lstCity, new { style = "width:150px" })*@
         @Html.DropDownListFor(m => m.Insert_DSA.CityCode, Model.lstCity, new { style = "width:150px" })
         @Html.ValidationMessageFor(m => m.Insert_DSA.CityCode)
         </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblWORKPHONE", "WORK PHONE")
        </div>
        <div class="col-md-6 col-sm-6">
       @* @Html.TextBox("txtWORKPHONE", "", new { style = "AutoCompleteType:disabled; MaxLength:11" })*@
       @Html.TextBoxFor(m => m.Insert_DSA.Office, new { @maxlength = 11 })
       @Html.ValidationMessageFor(m => m.Insert_DSA.Office)
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblmobile", "MOBILE")
        </div>
        <div class="col-md-6 col-sm-6">
        @Html.TextBoxFor(m => m.Insert_DSA.Mobile, new { @maxlength = 10 })
        </div>
    </div>
    <div id="phone" class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
       <label id="lblTELEPHONENOs">TELEPHONE NOs</label>
        </div>
        <div class="col-md-6 col-sm-6">
        @*<input type="text" name="txtTELEPHONENOs" id="txtTELEPHONENOs"/>*@
        @Html.TextBoxFor(m => m.Insert_DSA.Residence, new { @maxlength = 11 })
        </div>
        <button class= "btnAddMore" style="left:0px;position:relative;">Add More</button>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblPRODUCTHANDLED", "PRODUCT HANDLED")
        <font color="red">*</font>
        </div>
        <div class="col-md-6 col-sm-6">
        @*@Html.ListBox("lstbxProduct", Model.lstProduct, new { style = "width:150px" })*@
        @Html.ListBoxFor(m => m.Insert_DSA.ProductID, Model.lstProduct)
        @Html.ValidationMessageFor(m => m.Insert_DSA.ProductID)
        </div>
    </div><br/>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div class="col-md-6 col-sm-6">
        @Html.Label("lblACTIVEUSER", "ACTIVE USER")
        </div>
        <div class="col-md-6 col-sm-6">
       <label> @Html.RadioButtonFor(m => m.Insert_DSA.Active, "1", new { Checked = "checked" }) Yes</label><br />
        <label>@Html.RadioButtonFor(m => m.Insert_DSA.Active, "0") No </label>
        </div>
    </div><br/>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div  class="col-md-6 col-sm-6">
        @Html.Label("lblEmp", "Enter Employee Number Of:")
        <font color="red">*</font>
        </div>
        <div class="col-md-2 col-sm-2">
        @Html.Label("lblRSM", "RSM")
        </div>
        <div class="col-md-2 col-sm-2">
        @Html.Label("lblASM", "ASM")
        </div>
        <div class="col-md-2 col-sm-2">
        @Html.Label("lblSM", "SM")
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div  class="col-md-6 col-sm-6">
        <br />
        @Html.Label("lblComp", "Two out of these three are compulsory")
        </div>
        <div class="col-md-2 col-sm-2">
        <br />
         @Html.TextBoxFor(m => m.Insert_DSA.RSMId, new { @maxlength = 50 })
        <input type="hidden" id="hdnRsmID" />
        </div>
        <div class="col-md-2 col-sm-2">
        <br />
            @Html.TextBoxFor(m => m.Insert_DSA.ASMId, new { @maxlength = 50 })
          <input type="hidden" id="hdnASmID" />
        </div>
        <div class="col-md-2 col-sm-2">
        <br />
        @Html.TextBoxFor(m => m.Insert_DSA.SMId, new { @maxlength = 50 })
         <input type="hidden" id="hdnSmID" />
        </div>
    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">
        <div  class="col-md-6 col-sm-6">

        </div>
        <div class="col-md-2 col-sm-2">
         @Html.TextBoxFor(m => m.Insert_DSA.RSMName, new { @maxlength = 50 })
         @Html.HiddenFor(m => m.Insert_DSA.RSMEmail)
        </div>
        <div class="col-md-2 col-sm-2">
         @Html.TextBoxFor(m => m.Insert_DSA.ASMName, new { @maxlength = 50 })
         @Html.HiddenFor(m => m.Insert_DSA.ASMEmail)
        </div>
        <div class="col-md-2 col-sm-2">
        @Html.TextBoxFor(m => m.Insert_DSA.SMName, new { @maxlength = 50 })
        @Html.HiddenFor(m => m.Insert_DSA.SMEmail)
        </div>        

    </div>
    <div class="row" style="left:-5px;position:relative;text-align:left; width:80%">

        <div class="col-md-6 col-sm-6">
        @Html.Label("lblPassword", "Change Password At 1st Login", "SM")
        </div>
        <div class="col-md-6 col-sm-6">

        @Html.CheckBoxFor(m => m.Insert_DSA.ChkFlag, new {@checked="checked" })<b>Check this if you want to change password at first login</b>
        </div>
         @*<label style="left:-15px;position:relative;">Check this if you want to change password at first login</label>*@
    </div>
    <div class="row">
        <div id="save" class="col-md-6 col-sm-6" style="text-align:Right">
        <input name="submit"id="btnSubmit" class="buttons" type="submit" value="Save" style="height:22px ;width:50px"/>
        </div>
        <div id="update" class="col-md-6 col-sm-6" style="display:none;text-align:Right">
        <input name="submit" id="btnUpdate" class="buttons" type="submit" value="Update" style="height:22px ;width:50px"/>
        </div>
        <div class="col-md-6 col-sm-6" style="text-align:left">
        <button id="btnCancel" class="buttons" style="height:22px ;width:50px" >Cancel</button>
        </div>
    </div>
}

</div>
</center>

在模型中:

  public class Insert_DSA
    {
        public string[] ProductDesc { get; set; }
        public string Active { get; set; }
        public string ASMId { get; set; }
        public string ASMName { get; set; }
        public string ASMEmail { get; set; }
        public string RSMId { get; set; }
        public string RSMName { get; set; }
        public string RSMEmail { get; set; }
        public string SMId { get; set; }
        public string SMName { get; set; }
        public string SMEmail { get; set; }
        //public string UserId { get; set; }
        public bool  ChkFlag { get; set; }
        public string UserId { get; set; }
        public string Pending { get; set; }

}

在控制器中:

 [HttpPost]
        public ActionResult Save(Models.clsDSAMaster MyModel,string submit)
        {

            int ucount = 0;
            string data = "";
            var form=Request.Form["Insert_DSA.ChkFlag"].ToString();

            if (ModelState.IsValid)
            {
                if (submit == "Save")
                {
                    ucount = MyModel.Insert_DSA.addDSA(MyModel.Insert_DSA, Session["EmpCode"].ToString());
                    if (ucount > 0)
                    {
                        data = "Records have been sent to Checker and will be in effect post approval";
                    }
                    else
                    {
                        data = "There was an error in adding DSA";
                    }

                }
                else if (submit == "Update")
                {
                    MyModel.Insert_DSA.UpdateDSA(MyModel.Insert_DSA, Session["EmpCode"].ToString());
                    if (ucount > 0)
                    {
                        data = "Records have been sent to Checker and will be in effect post approval";
                    }
                    else
                    {
                        data = "There was an error in adding DSA";
                    }
                }
            }
            else
            {
                var errors = ModelState.Where(x => x.Value.Errors.Any()).Select(x => new { x.Key, x.Value.Errors });
            }
                return Content(data, "text/html");
        }

我没有手动完成此复选框的任何排序验证,但如果取消选中该复选框,则当正确验证的数据发布到控制器ModelState.IsValid时,属性仍为false。 当我使用

查找ModelState错误时
var errors = ModelState.Where(x => x.Value.Errors.Any()).Select(x => new { x.Key, x.Value.Errors });

它给了我

  

ChkFlag字段是必需的。

我想要的是什么: 我不希望复选框是必填字段,即使取消选中该复选框,我也希望ModelState.IsValid属性为真。

2 个答案:

答案 0 :(得分:1)

$("#btnAddDSA").click(function () {脚本中,您有以下

$(':input', '#form0').removeAttr('selected').not(':button, :submit, :reset, :hidden').val('');

正在将复选框的值从value="True"更改为value=""

现在,如果选中复选框,而不是表单数据

...&Insert_DSA.ChkFlag=True&Insert_DSA.ChkFlag=False

回帖

...&Insert_DSA.ChkFlag=&Insert_DSA.ChkFlag=False

请注意,Insert_DSA.ChkFlag=FalseCheckBoxFor()方法生成与value="False"相关联的隐藏输入的结果

现在,当DefaultModelBinder读取表单值时,它会找到属性Insert_DSA.ChkFlag的第一个匹配项,并尝试将其设置为空(null)值(相当于{{ 1}})当然失败了因为bool ChkFlag = null;只能有booltrue的值。因此,您的属性的值是默认值(false),因为无法设置其值,并且添加了false错误。

目前还不清楚此代码的用途是什么,但解决此问题的一种方法是排除ModelState(在input[type="checkbox"]选择器中)。

答案 1 :(得分:-1)

在MVC中,当取消选中该复选框时,它不会被添加到表单元素中,并且modelstate.isvalid将始终返回false。

您必须使用选中的值显式添加它为false。您可以检查控制器操作参数列表中是否有任何值。