2010-09-27 56 views
0

如何在asp.net MVC模式版本2中只讀取下拉菜單?如何在asp.net mvc中將下拉列爲只讀?

+0

通過@disabled在= 「禁用」 下拉框屬性作爲完成:<%= Html.DropDownList( 「PID」,計算機[ 「產品」]作爲的SelectList, 「選擇產品」,新的{@disabled =「禁用「,@ class =」wide「})%> – 2010-09-27 10:06:17

回答

0

你可以使用jquery禁用下拉菜單中的所有選項。

$("#DropdownID option").attr("disabled","true"); 

這將顯示的選項,但他們都沒有選擇..

0

這是不行的,禁用的下拉列表不會發布它的選擇上的表單崗位價值,如果模型屬性綁定到下拉列表中,模型的屬性值將作爲空值提交。

0

這是一箇舊帖子,但是...我的首選方法是禁用選項,而不是控件,以便將選定的值發回。

public static MvcHtmlString SecureDropDownListFor<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expression, 
    IEnumerable<SelectListItem> selectList, 
    string optionLabel, 
    object htmlAttributes, 
    bool alwaysReadonly) 
{ 
    bool isReadonly = !CurrentUserCanEdit(expression) || alwaysReadonly; 
    var attributes = new RouteValueDictionary(htmlAttributes); 
    if (isReadonly) 
    { 
     // This will pick up the style but not prevent a different option from being selected. 
     attributes.Add("readonly", "readonly"); 
    } 

    var retval = htmlHelper.DropDownListFor(expression, selectList, optionLabel, attributes); 

    // Disable all but the selected option in the list; this will allow user to see other options, but not select one 
    if (isReadonly) 
    { 
     retval = new MvcHtmlString(retval.ToHtmlString().Replace("option value=", "option disabled=\"disabled\" value=")); 
    } 
    return retval; 
} 

這樣做的效果是,用戶可以點擊下拉箭頭,看到未選擇的選項,但不能選擇其中任何一個。由於選擇本身沒有被禁用,只有選項,選定的值將被包含在回發中。

0

以下是一個解決方案,可以防止用戶在下拉列表中進行任何選擇,並仍然在表單文章中提交所選選項的值。

標記爲只讀的下拉列表。

@Html.DropDownListFor(model => Model.SomeID, new SelectList(ListOfOptions, "Value", "Text", Model.SomeID), new {@class = "disabled", @readonly = "readonly"}) 

或簡單地

<select class="disabled" readonly="readonly">...[All your options, one of them selected]...</select> 

然後一個jquery時將禁止未選定選項(即密鑰)。

$('select.disabled option:not(:selected)').attr("disabled", "true");