2013-11-04 49 views
0

我想知道是否有可能在隱藏字段上使用控件(dataanotation)(HiddenFor或hidden EditorFor)?MVC4 .Net,隱藏字段上的控件

我不這麼認爲,但我們永遠不知道。

有關於如何隱藏EditorFor如很多帖子: TextBoxFor vs EditorFor, and htmlAttributes vs additionalViewData

在我的情況下,在視圖中我有一個jquery調用一個WCF REST服務,在成功的情況下,填補我EditorFor。我希望在該EditorFor上應用Required DataAnotation,是否有可能?

我認爲只要EditorFor是不可見的,DataAnotation就不能應用。它是否有辦法在隱藏的EditorFor上應用DataAnotation?


下面是代碼: 要隱藏EditorFor:

@Html.EditorFor(model => model.VilleDepart, "CustomEditor", new {style = "display:none;" }) 

的CustomEditor:

@{ 
    string s = ""; 
    if (ViewData["style"] != null) { 
     // The ViewData["name"] is the name of the property in the addtionalViewData... 
     s = ViewData["style"].ToString(); 
    } 
} 

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { style = s }) 

模型:

string _VilleDepart; 
[Required] 
[Display(Name = "Ville Départ")] 
public string VilleDepart 
{ 
    get 
    { 
     if (Commune != null) { 
      return Commune.Commune1; 
     } 

     return _VilleDepart; 
    } 
    set { 
     _VilleDepart = value; 
    } 
} 

了jQuery調用WCF REST服務:

$(document).ready(function() { 
    $([document.getElementById("IVilleDepart"), document.getElementById("IVilleArrivee")]).autocomplete({ 
     source: function (request, response) { 
      $.ajax({ 
       cache: false, 
       type: "GET", 
       async: false, 
       dataType: "json", 
       url: GetSearchCommunetURl + "(" + request.term + ")", 
       success: function (data) { 
        //alert(data); 
        response($.map(data, function (item) { 
         return { 
          label: item['Commune'] + ' (' + item['CodePostal'] + ')', 
          val: item 
         } 
        })) 
       }, 
       error: function (response) { 
        alert("error ==>" + response.statusText); 
       }, 
       failure: function (response) { 
        alert("failure ==>" + response.responseText); 
       } 
      }); 
     }, 
     select: function (e, i) { 
      if (e.target.id == "IVilleDepart") { 
       VilleDepart = i.item.val; 
       EVilleDepart.value = VilleDepart.Commune; 
       ECodePostalDepart.value = VilleDepart.CodePostal; 
       ECodeINSEEDepart.value = VilleDepart.CodeINSEE; 

      } 
      if (e.target.id == "IVilleArrivee") { 
       VilleArrivee = i.item.val; 
       EVilleArrivee.value = VilleArrivee.Commune; 
       ECodePostalArrivee.value = VilleArrivee.CodePostal; 
       ECodeINSEEArrivee.value = VilleArrivee.CodeINSEE; 
      } 
     }, 
     minLength: 2 
    }); 
}); 

如果我不躲EditorFor我可以看到它是正確填寫的WCF REST服務調用後和所需DataAnotation應用。

還有其他的方法來隱藏EditorFor,例如應用的樣式=「寬度:0像素,高度:0像素」

它隱藏,但禁用所需DataAnotation,如果我申請的風格

='width:0px; height:1px',我們沒有看到很多EditorFor,但Required DataAnotation是活動的。

+1

我認爲無論EditorFor是否隱藏,DataAnnotation都應用於字段。你能發佈一些不工作的代碼,你的ViewModel和View嗎? – freshbm

+0

是的驗證仍然有效。 – WannaCSharp

+0

驗證似乎不工作在隱藏的領域,你會有一些例子驗證與HiddenFor的作品嗎? – fguigui

回答