2014-01-06 43 views
2

我有一個MVC 4中有一些可選部分的窗體。例如,表單用於插入新的人員記錄,但也有用於親屬和索賠的可選字段。我用複選框和一些jQuery隱藏和顯示這些表單的這些部分。因此頁面上的這些字段存在,但它在可見性屬性中的div是錯誤的。MVC 4 - 是否可以打開/關閉部分模型驗證?

相關模型

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" }) 

我用這個簡單的布爾支配,如果實體框架創建一個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 
     } 

摘要

關閉模型驗證的份,基於模型屬性控制器。可能嗎?

+0

http://stackoverflow.com/questions/12843282/conditional-validation-in-asp-net-mvc4 –

回答

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

讓我知道,如果它幫助。