MVC 4 - 是否可以打开/关闭模型验证的部分?

时间:2014-01-06 09:33:29

标签: asp.net-mvc-4 model data-annotations

我在MVC 4中有一个表单,它有一些可选部分。例如,表单用于插入新的人员记录,但也有亲戚和索赔的可选字段。我隐藏并使用复选框和一些jQuery显示表单的这些部分。因此,页面上的这些字段存在,但它在内部可见性属性中的div为false。

依赖模型

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Models
{
    public class ModelDependant
    {
        public Guid DependantID { get; set; }
        public Guid PersonID { get; set; }
        [Required]
        public string RelationToDependant { get; set; }
        [Required]
        public string Firstname { get; set; }
         [Required]
        public string Surname { get; set; }
         [Required]
        public string Address { get; set; }
        public string Borough { get; set; }
        public string PostCode { get; set; }
        public string Gender { get; set; }
        public string PrimaryLanguage { get; set; }
        public DateTime RegistrationDate { get; set; }
        [Required]
        [DisplayName("Date of birth")]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
        [DataType(DataType.Date)]
        public DateTime DateOfBirth { get; set; }
        public string Nationality { get; set; }
        public string Ethnicity { get; set; }
        public string Religion { get; set; }

        public bool boolSuccess { get; set; }
        public string strMessage { get; set; }
        public string strAction { get; set; }
        public bool boolDelete { get; set; }

    }
}

这些列表可以在此模型中

using Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Models
{
    public class modelClaimDatabase
    {
        public modelClaimDatabase()
        {
            modelPerson = new modelPerson();
            modelClaim = new modelClaim();
            LinkerStatusOfClaim = new List<LinkerStatusOfClaim>();
            modelClaimStatus = new List<modelClaimStatus>();
            modelPeopleGrid = new List<modelPeopleGrid>();
            ModelDependants = new List<ModelDependant>();
        }

        public modelPerson modelPerson { get; set; }
        public modelClaim modelClaim { get; set; }
        public List<modelClaimStatus> modelClaimStatus { get; set; }
        public List<LinkerStatusOfClaim> LinkerStatusOfClaim { get; set; }
        public List<modelPeopleGrid> modelPeopleGrid { get; set; }
        public List<ModelDependant> ModelDependants { get; set; }


        // Properties for controller
        public bool isValidModel { get; set; }


        public bool boolSuccess { get; set; }
        public string strMessage { get; set; }
        public string strAction { get; set; }

    }
}

以下是我与modelClaimDatabase绑定的视图

@model Models.modelClaimDatabase
<h4>
    @Html.Label("Edit details for: " + Model.modelPerson.Firstname + " " + Model.modelPerson.Surname)
</h4>

@using (Html.BeginForm())
{
    <div id="divPerson" style="padding: 5px;">
        @Html.HiddenFor(m => m.modelPerson.PersonID)
        @Html.LabelFor(m => m.modelPerson.Salutation)
        @Html.DropDownListFor(m => m.modelPerson.Salutation, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="Mr", Value = "Mr" }, 
                        new SelectListItem{ Text="Mrs", Value = "Mrs" },
                        new SelectListItem{ Text="Miss", Value = "Miss" },
                        new SelectListItem{ Text="Ms", Value = "Ms" },
                        new SelectListItem{ Text="Dr", Value = "Dr" }
                     })

        @Html.LabelFor(m => m.modelPerson.Firstname)
        @Html.TextBoxFor(m => m.modelPerson.Firstname)
        <br />
        @Html.ValidationMessageFor(m => m.modelPerson.Firstname)

        @Html.LabelFor(m => m.modelPerson.Surname)
        @Html.TextBoxFor(m => m.modelPerson.Surname)
        <br />
        @Html.ValidationMessageFor(m => m.modelPerson.Surname)

        @Html.LabelFor(m => m.modelPerson.TelephoneNumber)
        @Html.TextBoxFor(m => m.modelPerson.TelephoneNumber)
        <br />
        @Html.ValidationMessageFor(m => m.modelPerson.TelephoneNumber)

        @Html.LabelFor(m => m.modelPerson.AltTelephoneNumber)
        @Html.TextBoxFor(m => m.modelPerson.AltTelephoneNumber)

        @Html.LabelFor(m => m.modelPerson.Address)
        @Html.TextAreaFor(m => m.modelPerson.Address)
        <br />
        @Html.ValidationMessageFor(m => m.modelPerson.Address)

        @Html.LabelFor(m => m.modelPerson.PostCode)
        @Html.TextBoxFor(m => m.modelPerson.PostCode)
        <br />
        @Html.ValidationMessageFor(m => m.modelPerson.PostCode)

        @Html.LabelFor(m => m.modelPerson.PrimaryLanguage)
        @Html.DropDownListFor(m => m.modelPerson.PrimaryLanguage, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="Spanish", Value = "Spanish" }, 
                        new SelectListItem{ Text="English", Value = "English" },
                        new SelectListItem{ Text="French", Value = "French" },
                        new SelectListItem{ Text="Italian", Value = "Italian" },
                        new SelectListItem{ Text="Portugese", Value = "Portugese" }
                     })
        <br />
        @Html.ValidationMessageFor(m => m.modelPerson.PrimaryLanguage)

        @Html.LabelFor(m => m.modelPerson.OtherLanguage)
        @Html.DropDownListFor(m => m.modelPerson.OtherLanguage, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="English", Value = "Spanish" }, 
                        new SelectListItem{ Text="Spanish", Value = "English" },
                        new SelectListItem{ Text="French", Value = "French" },
                        new SelectListItem{ Text="Italian", Value = "Italian" },
                        new SelectListItem{ Text="Portugese", Value = "Portugese" }
                     })

         @Html.LabelFor(m => m.modelPerson.DateOfBirth)
        @Html.TextBoxFor(m => m.modelPerson.DateOfBirth, new { @class = "datepicker" })
        <br />
        @Html.ValidationMessageFor(m => m.modelPerson.DateOfBirth)

        @Html.LabelFor(m => m.modelPerson.Nationality)
        @Html.DropDownListFor(m => m.modelPerson.Nationality, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="English", Value = "Spanish" }, 
                        new SelectListItem{ Text="Spanish", Value = "English" },
                        new SelectListItem{ Text="French", Value = "French" },
                        new SelectListItem{ Text="Italian", Value = "Italian" },
                        new SelectListItem{ Text="Portugese", Value = "Portugese" }
                     })

        @Html.LabelFor(m => m.modelPerson.OtherNationality)
        @Html.DropDownListFor(m => m.modelPerson.OtherNationality, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="English", Value = "Spanish" }, 
                        new SelectListItem{ Text="Spanish", Value = "English" },
                        new SelectListItem{ Text="French", Value = "French" },
                        new SelectListItem{ Text="Italian", Value = "Italian" },
                        new SelectListItem{ Text="Portugese", Value = "Portugese" }
                     })


        @Html.LabelFor(m => m.modelPerson.Ethnicity)
        @Html.DropDownListFor(m => m.modelPerson.Ethnicity, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="White", Value = "White" }, 
                        new SelectListItem{ Text="Black", Value = "Black" },
                        new SelectListItem{ Text="Mixed-Race", Value = "Mixed-Race" },
                        new SelectListItem{ Text="Indian", Value = "Indian" },
                        new SelectListItem{ Text="Chinese", Value = "Chinese" }
                     })

        @Html.LabelFor(m => m.modelPerson.Religion)
        @Html.DropDownListFor(m => m.modelPerson.Religion, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="Christian", Value = "Christian" }, 
                        new SelectListItem{ Text="Muslim", Value = "Muslim" },
                        new SelectListItem{ Text="Jewish", Value = "Jewish" },
                        new SelectListItem{ Text="Hindu", Value = "Hindu" },
                        new SelectListItem{ Text="Sikh", Value = "Sikh" }
                     })


        @Html.LabelFor(m => m.modelPerson.HasDisability)
        @Html.CheckBoxFor(m => m.modelPerson.HasDisability, new { @id = "chkHasDisability" })

        <div id="divDisability" style="border-style: solid; border-width: thin; padding: 5px;">
            @Html.Label("Please provide more details")
            @Html.LabelFor(m => m.modelPerson.Disability)
            @Html.EditorFor(m => m.modelPerson.Disability)

        </div>

        @Html.LabelFor(m => m.modelPerson.HasDependants)
        @Html.CheckBoxFor(m => m.modelPerson.HasDependants, new { @id = "chkHasDependants" })



        <hr />
        <div id="divDependants" style="border-style: solid; border-width: thin; padding: 5px;">
            <div style="background-color: #C8C8C8">
                @Html.Label("Dependants data")
            </div>
            <br />
            <input type="submit" value="Add dependant" name="btnSubmit" />

            <br />
            <hr />
            @for (int i = 0; i < Model.ModelDependants.Count; i++)
            {
                int status = i + 1;



                <table>
                    <tr>
                    <td>@Html.Label("Dependant: " + status.ToString()) </td>
                        <td>@Html.Label("Delete this dependant:")
                        </td>
                        <td>@Html.CheckBoxFor(m => m.ModelDependants[i].boolDelete)</td>
                    </tr>
                </table>



                <br />@*
                 <input type="submit" value="Remove Dependant @status.ToString()" name="btnSubmit" />*@

                @Html.HiddenFor(m => m.ModelDependants[i].PersonID)
                @Html.HiddenFor(m => m.ModelDependants[i].DependantID)
                @Html.LabelFor(m => m.ModelDependants[i].RelationToDependant)
                @Html.EditorFor(m => m.ModelDependants[i].RelationToDependant)

                @Html.LabelFor(m => m.ModelDependants[i].Firstname)
                @Html.EditorFor(m => m.ModelDependants[i].Firstname)

                @Html.LabelFor(m => m.ModelDependants[i].Surname)
                @Html.EditorFor(m => m.ModelDependants[i].Surname)

                @Html.LabelFor(m => m.ModelDependants[i].DateOfBirth)
                @Html.TextBoxFor(m => m.ModelDependants[i].DateOfBirth, new { @class = "datepicker" })

                @Html.LabelFor(m => m.ModelDependants[i].Address)
                @Html.EditorFor(m => m.ModelDependants[i].Address)

                @Html.LabelFor(m => m.ModelDependants[i].Borough)
                @Html.EditorFor(m => m.ModelDependants[i].Borough)

                @Html.LabelFor(m => m.ModelDependants[i].PostCode)
                @Html.EditorFor(m => m.ModelDependants[i].PostCode)

                @Html.LabelFor(m => m.ModelDependants[i].Gender)
                @Html.DropDownListFor(m => m.ModelDependants[i].Gender, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="Male", Value = "Male" }, 
                        new SelectListItem{ Text="Female", Value = "Female" }
                     })

                @Html.LabelFor(m => m.ModelDependants[i].PrimaryLanguage)
                @Html.DropDownListFor(m => m.ModelDependants[i].PrimaryLanguage, new List<SelectListItem>
                     {
                        new SelectListItem{ Text="Spanish", Value = "Spanish" }, 
                        new SelectListItem{ Text="English", Value = "English" },
                        new SelectListItem{ Text="French", Value = "French" },
                        new SelectListItem{ Text="Italian", Value = "Italian" },
                        new SelectListItem{ Text="Portugese", Value = "Portugese" }
                     })
                <br />

                <hr />
            }
            <br />


        </div>

    </div>

    <input type="submit" value="Edit person record" name="btnSubmit" />
}

@* Date JS Logic *@
<script type="text/javascript">
    $(function () {
        $(".datepicker").datepicker({
            dateFormat: "dd/mm/yy",
            showStatus: true,
            showWeeks: true,
            currentText: 'Now',
            autoSize: true,
            gotoCurrent: true,
            showAnim: 'drop',
            highlightWeek: true,
            changeMonth: true,
            changeYear: true
        });
        $("#anim").change(function () {
            $(".datepicker").datepicker("option", "showAnim", $(this).val());
        });
    });
</script>

<script type="text/javascript">
    function hideGenericLbl() {
        $("#lblGenericMessage").css("color", "red");
        $("#lblGenericMessage").fadeOut(5000);
    }

    $(document).ready(function () {
        hideGenericLbl();

        @if (Model.ModelDependants.Count > 0)
        {
             @:$("#chkHasDependants").prop('checked', true);
                }

        @if (Model.strMessage != null)
        {
            if (Model.isValidModel == false &&
            Model.strMessage.Contains("Must be at least one claim status if making a claim.") ||
            Model.strMessage.Contains("New claim status available") ||
            Model.strMessage.Contains("One claim status removed."))
            {
                @:$("#modelClaim_ClaimMade").prop('checked', true);
                        @:$("#modelPerson_HasDependants").prop('checked', true);
            }
        }

        $("#divClaimType").hide();
        $("#divClaimStatus").hide();
        $("#divDisability").hide();
        $("#divDependants").hide();

        // Claims
        if ($('#modelClaim_ClaimMade').is(':checked')) {
            $("#divClaimType").show();
            $("#divClaimStatus").show();
        }
        else {
            $("#divClaimType").hide();
            $("#divClaimStatus").hide();
        }
        // Disability
        if ($('#chkHasDisability').is(':checked')) {
            $("#divDisability").show();
        }
        else {
            $("#divDisability").hide();
        }

        // Dependants
        if ($('#chkHasDependants').is(':checked')) {
            $("#divDependants").show();
        }
        else {
            $("#divDependants").hide();
        }

    });
    // Claim made logic
    $("#modelClaim_ClaimMade").click(function () {
        if ($('#modelClaim_ClaimMade').is(':checked')) {
            $("#divClaimType").show();
            $("#divClaimStatus").show();
        }
        else {
            $("#divClaimType").hide();
            $("#divClaimStatus").hide();
        }
    });
    //Disability logic
    $("#chkHasDisability").click(function () {
        if ($('#chkHasDisability').is(':checked')) {
            $("#divDisability").show();
        }
        else {
            $("#divDisability").hide();
        }
    });

    //Dependant logic
    $("#chkHasDependants").click(function () {
        if ($('#chkHasDependants').is(':checked')) {
            $("#divDependants").show();
        }
        else {
            $("#divDependants").hide();
        }
    });
</script>

在我的屏幕截图中,依赖者正在使用

 @Html.CheckBoxFor(m => m.modelPerson.HasDependants, new { @id = "chkHasDependants" })

我使用这个简单的布尔值来指示Entity框架是否创建了一个depandant。

有没有办法根据此布尔值关闭/打开控制器中的验证器?

Required fields

最后,这是我的控制器(IsModelState.Valid)条件

[HttpPost]
        public ActionResult Index(string btnSubmit, FormCollection collection, modelClaimDatabase Model)
        {
            RepositoryClient RC = new RepositoryClient();
            switch (btnSubmit)
            {
                case "Add dependant":
                    #region AddDependant
                    // Get Claim types for VIEW
                    GetClaims(Model);
                    //Add new claim to list
                    Model.ModelDependants.Insert(Model.ModelDependants.Count, new ModelDependant());
                    // SET to false as Model is not ready for DB
                    Model.isValidModel = false;

                    // SET message for the user
                    Model.strMessage = "One dependant association added.";
                    return View("Index", Model);
                    #endregion
                case "Remove dependant":
                    #region RemoveDependant
                    // Can't remove IF only 1 
                    Model.isValidModel = false;
                    GetClaims(Model);
                    if (Model.ModelDependants.Count == 1)
                    {
                        Model.strMessage = "Must be at least one dependant if person has dependants.";
                    }
                    else
                    {
                        Model.ModelDependants.RemoveAt(Model.ModelDependants.Count - 1);
                        Model.strMessage = "One dependant association removed.";

                    }
                    return View("Index", Model);
                    #endregion
                case "Add claim status":
                    #region AddClaimStatus
                    // Get Claim types for VIEW
                    GetClaims(Model);
                    //Add new claim to list
                    Model.LinkerStatusOfClaim.Insert(Model.LinkerStatusOfClaim.Count, new LinkerStatusOfClaim());
                    // SET to false as Model is not ready for DB
                    Model.isValidModel = false;
                    // SET message for the user
                    Model.strMessage = "New claim status available";
                    return View("Index", Model);
                    #endregion
                case "Remove claim status":
                    #region RemoveClaimStatus
                    // Can't remove IF only 1 
                    Model.isValidModel = false;
                    GetClaims(Model);
                    if (Model.LinkerStatusOfClaim.Count == 1)
                    {
                        Model.strMessage = "Must be at least one claim status if making a claim.";
                    }
                    else
                    {
                        Model.LinkerStatusOfClaim.RemoveAt(Model.LinkerStatusOfClaim.Count - 1);
                        Model.strMessage = "One claim status removed.";

                    }
                    return View("Index", Model);
                    #endregion
                case "Save person record to database":
                    #region submit
                    GetClaims(Model);
                    Model.isValidModel = ModelState.IsValid;
                    if (ModelState.IsValid)
                    {
                        // First create a new person record
                        RC.CreatePerson(Model);

                        // Only do other inserts if Person successfully created.
                        switch (Model.modelPerson.HasDependants && Model.modelPerson.boolSuccess)
                        {
                            case true:
                                RC.CreateDependant(Model);
                                break;
                            case false:
                                Model.ModelDependants.RemoveAt(0);
                                break;
                        }

                        switch (Model.modelClaim.ClaimMade && Model.modelPerson.boolSuccess)
                        {
                            case true:
                                RC.CreateClaim(Model);
                                break;
                            case false:
                                Model.LinkerStatusOfClaim.RemoveAt(0);
                                break;
                        }

                        // Do one final check before going to success screen
                        if (!Model.modelPerson.boolSuccess)
                        {
                            return View("Index", Model);
                        }
                    }
                    else
                    {
                        Model.strMessage = "Person data could not be inserted into the database. Missing key fields.";
                        return View("Index", Model);
                    }

                    // Use to persist data through redirect - Model data will be lost otherwise
                    TempData["Model"] = Model;
                    return RedirectToAction("Success");

            }
            return View();
                    #endregion
        }

摘要

根据模型属性关闭模型验证的部分内容。有可能吗?

1 个答案:

答案 0 :(得分:0)

一个选项是Matt引用的foolproof,它在客户端和服务器端提供简单的条件验证。

如果您只想在客户端禁用验证或出于任何原因您不想使用万无一失的插件,那么还有一种脏的JavaScript方式:

if(condition){
    $("#Property1").rules("remove");  //This will remove validation for the specific input
    //...
}

在你的情况下,我们也可能会这样:

$("#Property1").change(function(){
    $("#Property2").rules("remove");
    //...
});

确保这些javascript代码在您的jquery.validation.js

之后出现

如果有帮助,请告诉我。