2013-04-10 67 views
1

我已經繼承了一半完成的MVC項目,該項目將跟蹤我們客戶產品的許可證。asp.net mvc 3複合顯示成員的下拉列表?

許可Create.cshtml頁面上有兩個下拉列表,其中第一個允許您選擇一個客戶,然後第二個列表填充客戶擁有的產品(CustomerProducts)以允許您選擇哪個CustomerProduct希望創建一個許可證,如下所示:

<div class="editor-label">Customer</div> 
<div class="editor-field"> 
    @Html.DropDownListFor(model => model.SelectedCustomerId, new SelectList(Model.Customers, "Id", "Name"), "-- Select Customer --") 
    @Html.ValidationMessageFor(model => model.SelectedCustomerId) 
</div> 

<div class="editor-label">Product</div> 
<div class="editor-field"> 
    @Html.DropDownListFor(model => model.SelectedCustomerProductId, Enumerable.Empty<SelectListItem>(), "-- Select Product --") 
    @Html.ValidationMessageFor(model => model.SelectedCustomerProductId) 
</div> 

我運行到的是,CustomerProducts與既有產品一個版本,但相關的下拉列表只顯示產品名稱,而不是問題版本名稱,因此如果客戶擁有「產品名稱v1.0」和「產品名稱v1.1」,則下拉菜單僅顯示兩次產品名稱。那麼我會尋找的是類似的信息(僞):

@Html.DropDownListFor(model => model.SelectedCustomerProductId + " (" + model.SelectedCustomerProductId.ProductVersion.Name + ")", Enumerable.Empty<SelectListItem>(), "-- Select Product --") 

我敢肯定,必須有一個簡單的方法來獲取下拉同時顯示產品和版本,但我已經沖刷和沖刷我能想到的每一個來源都無法提出解決方案。

道歉,如果這是一個基本的問題;我是MVC的新手,花了幾天的時間尋找解決方案,看起來應該是一個非常簡單的問題!

編輯:下面的

上@von v跟進的建議,增加了一個只讀屬性CustomerProduct:

public virtual string ProductVersionFullName { get { return Product.Name + " (" + ProductVersion.Name + ")"; } } 

然後只需使用該屬性作爲的情況下,顯示成員,而不是嘗試在下拉列表中綁定到CustomerProduct的多個屬性(下拉列表由顯示成員設置的LicensesController中的方法填充)。我知道我錯過了一些簡單的事情!

回答

2

DropDownListFor的第一個參數定義爲

標識包含的屬性的對象的表達式 顯示

如果你正在尋找到的是,可以讓你困惑。但基本上,第一個參數是「指向」您的模型的屬性,您希望將下拉的值綁定到的表達式。在你的情況下,你的模型有一個屬性SelectedCustomerProductId,這是下拉的選定值將被「放入」的位置。這應該是一個單一的財產。如果您想在下拉列表中顯示更多文本,則需要將其構建到selectlistitem中。

所以在您的控制器的方法,你會碰到這樣的:

// this is where you build your model 
var model =initializeYourModel(); 

// this is where you build the Products 
// whose values are used in the DropDownList. 
// I assume you already have the code that builds the list, 
// this is just an example that shows 
// where you should build the "Product and the Version" 
model.Products = new List<SelectListItem> 
{ 
    new SelectListItem{ Value = "1", Text = "the name " + "the version"}, 
}; 
+1

謝謝,我覺得* *這是足以讓我再次感動。當我有一個工作解決方案時,我會發布代碼。 – technophebe 2013-04-10 12:10:35

+0

很高興幫助你,並幫助你。 – 2013-04-10 12:13:03

+1

是的,一旦你指向正確的方向就明顯了!已編輯我的問題,包括解決方案。再次感謝。 – technophebe 2013-04-10 13:13:01