[英]How to make a form responsive (show/hide portion of the form) based on the selected items from a drop down list?
我正在ac#mvc項目中的剃刀視圖上工作,並且我想根據從下拉列表中選擇的值對項目(文本框等)做出響應。
這是我的剃刀視圖中的下拉列表:
<div class="form-group">
@Html.LabelFor(a=> a.pm_main_rep.PM_Event_CategoriesId)
@Html.DropDownListFor(a=>a.pm_main_rep.PM_Event_CategoriesId, new SelectList(Model.pm_evt_catgrss, "Id","type_of_event"), "Select a category", new { @class="form-control"})
</div>
現在,此下拉列表從數據庫填充了一些值,例如會議,培訓等。
我現在想要的是,如果用戶從上面的下拉列表中選擇會議,則用於選擇日期的下面的文本框應該出現。
@if(?????)
{
<div class="form-group">
@Html.LabelFor(a => a.pm_main_rep.Estimated_Start_Date)
@Html.TextBoxFor(a => a.pm_main_rep.Estimated_Start_Date, "Start Date", new { @class = "form-control", @readonly = "readonly", @style = "cursor :default;" })
</div>
}
if()塊中的邏輯應該是什么,或者如果有更好的方法,請告訴我。 謝謝
有兩個選項-取決於您要在服務器端還是客戶端在哪里執行操作。 如果每種選擇都有很多數據要發送給客戶端,那么我建議使用服務器端,否則,不需要使用客戶端。
1)在服務器端,每次用戶從列表中選擇其他選項時,都應發布該表單。 我展示了如何通過ajax從服務器發送HTML來執行此操作,但是您也可以從服務器發送JSON並使用js進行解析。 我正在使用jquery:
JS:
$('#Estimated_Start_Date').change(function() {
$.post('/.../gethtmlfordropdown', { selection: $('#Estimated_Start_Date').val() }, function(html) {
$('#Choice').html(html);
});
});
CSHTML:
<div class="form-group">
@Html.LabelFor(a=> a.pm_main_rep.PM_Event_CategoriesId)
@Html.DropDownListFor(a=>a.pm_main_rep.PM_Event_CategoriesId, new SelectList(Model.pm_evt_catgrss, "Id","type_of_event"), "Select a category", new { @class="form-control"})
</div>
<div id="Choice"><!-- Content from ajax --></div>
服務器:
public ActionResult GetHtmlForDropDown(string selection)
{
string html = ...; // Get the html depending on 'selection'
return PartialView(html);
}
2)在客戶端-為每個內容提供ID,如果ID等於下拉菜單中的選擇值,則更容易,例如:
CSHTML:
<div class="form-group">
@Html.LabelFor(a=> a.pm_main_rep.PM_Event_CategoriesId)
@Html.DropDownListFor(a=>a.pm_main_rep.PM_Event_CategoriesId, new SelectList(Model.pm_evt_catgrss, "Id","type_of_event"), "Select a category", new { @class="form-control"})
</div>
<div class="choice" id="Value1" style="display: none;">...</div>
<div class="choice" id="Value2" style="display: none;">...</div>
<div class="choice" id="Value3" style="display: none;">...</div>
JS:
$('#Estimated_Start_Date').change(function() {
var selection = $('#Estimated_Start_Date').val();
$('.choice').css({ 'display': 'none' })
.filter('#' + selection).css({ 'display': 'block' });
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.