2011-12-21 30 views
3

廣泛的不成功的搜索後,我希望你們能幫助我在這裏...如何使用dropdownlist中的對象屬性來選擇工具提示?

我所知道的:有可能通過

<script type="text/javascript"> 
    $(function() { 
     $("#someDropDownForList option").each(function() {    
     $(this).attr({ 'title': $(this).html() }); 
     }); 
    }); 
</script> 

產生的下拉列表選項提示。然而,在我的情況我要爲用戶提供更多的信息,用戶在

<html>  
    <body> 
     <div> 
     @Html.DropDownListFor(
     m => m.SomeModelProperty, 
     new selectList(Model.ListWithObjects, "Property1", "Property1"), 
     new { @id="someDropDownForList"}) 
     </div> 
    </body> 
</html> 

我如何使用jQuery使用Property2和Property3構建每個選項的工具提示文本的選項?

Property1 + " has: " + Property2 + " and " Property3 

隨着親切的問候,

保羅

編輯:沒有的jQuery

<div> 
    <select id="someDropDownForList "> 
    @foreach(var item in Model.ListWithObjects) 
    { 
    <option title="Some property is the @item.Property2: with the @item.Property3"> 
     @item.Property1 
    </option>   
    }   
    </select> 
</div> 
+0

但是「property2」和「property3」是什麼? '新SelectList()'中的第二個參數是'

+0

我很抱歉沒有提供這些信息。 Model.ListWithObjects由具有三個(字符串)屬性的對象組成:Property1,2和3.因此,下拉列表顯示屬性1的字符串值,我想在工具提示中使用剩餘的兩個屬性。 – Paul 2011-12-21 13:40:42

+0

使用var應該工作...我可以做一些像'var Property2 ='@ Model.ListWithObjects [0] .Property2'',我無法用排序索引替換0(如:var index = $(this).index();')雖然...任何想法? – Paul 2011-12-21 15:15:40

回答

3

所提供的幫助Html.DropDownListFor只允許綁定通過IEnumerable<SelectListItem> selectList參數<option>文本和值(一個解決方案如你所做的那樣)。

問題是,您無法從客戶端JavaScript訪問模型中的其他屬性。 Javascript不知道你的C#對象。

我認爲正確的方法是將生成以下HTML:

<select> 
    <option value="ValueProperty1" title="Property1 has: Property2 and Property3">TextProperty1</option> 
    ... 
</select> 

你甚至不需要任何的jQuery。

如何實現這一目標?我認爲你最好通過擴展SelectListItem來實現一個可靠的解決方案,並創建一個新的幫助器方法來生成DropDownList。

以下回答確實如此:Adding html class tag under in Html.DropDownList

+0

的輸出謝謝你,我想知道jquery解決方案是否可能也用於教育目的;))。我已經轉向了一個foreach循環來至少獲得有用的功能。爲了完整性,我在原文中添加了一段代碼。 – Paul 2011-12-22 08:36:32

相關問題