2017-09-29 110 views
0

我在MVC 5.創建窗體下面有一個文本框:MVC 5隱藏文本框

<div class="form-group"> 
     @Html.LabelFor(model => model.Client_PID, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 

      @Html.EditorFor(model => model.Client_PID, new { htmlAttributes = new { @class = "form-control" } }) 
      @Html.ValidationMessageFor(model => model.Client_PID, "", new { @class = "text-danger" }) 

     </div> 
</div> 

我想使這個用默認值有條件無形的,否則被填寫客戶。

完成此操作的最佳方法是什麼?我已經能夠使文本框有條件地隱藏,但是然後我的表單失敗,如果(ModelState.IsValid)無效, ...我如何將默認值傳遞給此?

+0

你想要什麼默認值?這可能會在controller actionresult方法中設置。你可以發佈這個呢? –

回答

1

您可以使用HiddenFor當你希望它是隱藏的,在其他情況下,你可以生成文本框,例如:

@if(ShouldBeVisible) 
{ 
    @Html.EditorFor(model => model.Client_PID, new { htmlAttributes = new { @class = "form-control" } }) 
    @Html.ValidationMessageFor(model => model.Client_PID, "", new { @class = "text-danger" }) 
} 
else 
{ 
    @Html.HiddenFor(model => model.Client_PID,1) 
} 

現在就bool基礎,我們正在創建隱藏字段,並設置它的默認值,否則它會生成文本框,用戶需要填寫值。

希望它有幫助!

0

您還可以通過輸入複選框和jQuery函數來控制此顯示/隱藏效果及其目標默認值。

<label for="hidden"> 
    <input type="checkbox" id="hidden" class="display-hidden" data-target=".hidden" /> 
    Show Client ID? 
</label> 

<div class="form-group hidden"> 
    @Html.LabelFor(model => model.Client_PID, htmlAttributes: new { @class = "control-label col-md-2" }) 
    <div class="col-md-10"> 
     @Html.EditorFor(model => model.Client_PID, new { htmlAttributes = new { @class = "form-control" } }) 
     @Html.ValidationMessageFor(model => model.Client_PID, "", new { @class = "text-danger" }) 
    </div> 
</div> 

然後jQuery函數:

$(".display-hidden").click(function() { 
    var target = $(this).attr("data-target"); 
    if($(this).is(':checked'){ 
     $(target).fadeIn(320); 
    } else { 
     $(target).fadeOut(320); 
     $(target).val(//your default value); 
    } 
}); 
+0

使用jQuery函數的好處在於,您可以在以後再次使用它。 – Tiramonium

+0

你應該在整個'.form-group'上放置'.hidden',因爲它會更好的用戶體驗。 –

+0

是的,你說得對,我忘了那個。 – Tiramonium

0

下面是我做到了......我理解了它之前,我看着你真棒答案...謝謝你的幫助!

@if(真) { 放在申請 } 其他 { @ Html.EditorFor(型號=> model.Client_PID,新{htmlAttributes = {新風格= 「顯示:無」}} ) }

也許這不是最佳實踐?