2012-07-05 104 views
19

我有一個ASP.NET MVC應用程序。我在我的頁面中有多個下拉列表(HTML選擇),我必須禁用它們,隨着用戶的繼續逐一選擇它們。當用戶將其發回給控制器時,我得到null作爲函數(操作方法)參數。我搜索並發現HTML不會在表單數據中發送禁用字段的值。用readonly替換禁用的屬性將不起作用,因爲它會使下拉工作。在asp.net中獲取禁用下拉列表的值mvc

我正在用戶繼續動態使用JavaScript生成下拉列表。所以沒有一個下拉菜單,但用戶需要的數量是多少。

有人可以告訴我應該如何獲得值?

回答

40

一種可能性是使下拉列表disabled="disabled",包括具有相同的名稱和價值,這將使該值發送到服務器的隱藏字段:

@Html.DropDownListFor(x => x.FooId, Model.Foos, new { disabled = "disabled" }) 
@Html.HiddenFor(x => x.FooId) 

如果必須禁用動態下拉使用javascript,只需在禁用它之後將當前選定的下拉列表的值分配給隱藏字段即可。

3

這是禁用控件的默認行爲。我建議你添加一個隱藏字段,並在這個隱藏字段中設置你的DropDownList的值並使用它。

喜歡的東西:

//just to create a interface for the user 
@Html.DropDownList("categoryDump", (SeectList)ViewBag.Categories, new { disabled = "disabled" }); 
// it will be send to the post action 
@Html.HiddenFor(x => x.CategoryID) 
0

您還可以創建它接受一個bool disabled參數和做繁重的你自己DropDownListFor超負荷所以你的觀點是不是堆滿了if disablethisfield then ...。這些線路中

事情可以做:

public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, bool disabled) 
{ 
    if (disabled) 
     return MvcHtmlString.Create(htmlHelper.HiddenFor(expression).ToString() + htmlHelper.DropDownListFor(expression, selectList, new { disabled="disabled" }).ToString()); 
    else 
     return htmlHelper.DropDownListFor(expression, selectList); 
} 

有6個重載單獨DropDownListFor所以這是一個很大的monkeycoding,但它到底恕我直言不負有心人。

-2

提交之前致電$('#FooId')。removeAttr('disabled')