2015-09-28 77 views
0

我試圖在觸發更改事件後將下拉列表呈現爲diabled。我在httppost上的控制器的viewbag中傳遞了禁用標誌。但是,viewbag的名稱顯示在html標誌中,而不僅僅是值。請參閱我下面的代碼:使用viewbag禁用html屬性

@Html.DropDownList("dropdown", ViewData["dropdown"] as IEnumerable<SelectListItem>, "--Select--", new { @class = "form-control", id = "dropbox", onchange = "this.form.submit();", ViewBag.propertydisable}) 

在我的控制器

ViewBag.propertydisable = "disabled"; 

它是如何呈現HTML:

<select class="form-control" id="dropbox" name="searchparams" propertydisable="disabled" onchange="this.form.submit();" > 
    <option value="">--Select Budget holder--</option> 
    <option selected="selected" value="option1">option1</option> 
    <option value="opt">option2</option> 
</select> 

我是多麼希望它渲染是

<select class="form-control" id="dropbox" name="searchparams" disabled onchange="this.form.submit();"> 
    <option value="">--Select Budget holder--</option> 
    <option selected="selected" value="option1">option1</option> 
    <option value="opt">option2</option> 
</select> 

因此,一旦回發完成,最終結果將被禁用。

回答

3

你需要建立一個基於對象的ViewBag財產

@{ var attributes = ViewBag.propertydisable ? (object)new { @class = "form-control", disabled = "disabled"} : (object)new { @class = "form-control"}; } 
@Html.DropDownList("dropdown", ViewData["dropdown"] as IEnumerable<SelectListItem>, "--Select--", attributes) 

請注意,您應該設置ViewBag財產

ViewBag.propertydisable = true; 

旁註定義HTML屬性:使用Unobtrusive Javascript而不是用行爲污染你的標記。不知道爲什麼你從默認"dropdown"改變id屬性"dropbox"但下面假設你刪除id="dropbox"屬性

$('#dropdown').change(function() { 
    $('#form').submit(); 
}); 
1

首先,而不是內聯腳本使用不顯眼的js。而且你也使用錯誤的超載。

下面的代碼應該工作:

@Html.DropDownList("dropdown",yourlist,new { @class = "form-control", id = "dropbox",disabled=ViewBag.propertydisable}) 

更新:

$(document).ready(function() { 
 

 

 
      $('#dropdown').change(function() { 
 

 
       $('#form').submit(); 
 

 
      });

+0

我已嘗試和財產來爲禁用無回傳被觸發,甚至當我設置viewbag值爲false。 – snab

+1

@ user2055227沒錯,只要「禁用」的存在將會禁用它,而不管「=」後面的部分。 – Crowcoder

+0

所以它的js代碼是錯誤的。請參閱更新代碼 –

0

似乎哈克給我,但你可以有條件地通過改變你propertydisable渲染元素這樣a bool:

@{ 
    if(Viewbag.propertydisable) 
    { 
     Html.DropDownList("dropdown", 
      ViewData["dropdown"] as IEnumerable<SelectListItem>, 
      "--Select--", 
      new { @class = "form-control", 
        id = "dropbox", 
        onchange = "this.form.submit();", 
        disabled = "disabled"}); 
     } 
    else 
    { 
     Html.DropDownList("dropdown", 
      ViewData["dropdown"] as IEnumerable<SelectListItem>, 
      "--Select--", 
      new { @class = "form-control", 
        id = "dropbox", 
        onchange = "this.form.submit();"}); 
    } 
}