回答

0

權,如果你在代碼生成列表後面,你給每個選項的唯一標識符,那麼你就可以搶標識,且具有在代碼和項目因此文本嫁給它。

所以;

public class MonthlyItemsFormViewModel 
{ 
    public SelectList Months; 
    public string SelectedMonth {get;set;} 
} 

然後;

public ActionResult Index() 
{ 
    MonthlyItemsFormViewModel fvm = new MonthlyItemsFormViewModel(); 
    FillData(fvm, DateTime.Now); 
    return View(fvm); 
} 

然後;

private void FillData(MonthlyItemsFormViewModel fvm, DateTime SelectedMonth) 
{ 
    List<string> months = DateTime.Now.MonthList(DateTime.Now); 
    fvm.Months = new SelectList(months, fvm.SelectedMonth); 
} 

然後在你看來;

<% using (Html.BeginForm()) { %> 
    <%=Html.DropDownList("selectedMonth", Model.Months) %> 
<%} %> 

然後在回覆;

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult Index(FormCollection collection) 
{ 
    MonthlyItemsFormViewModel fvm = new MonthlyItemsFormViewModel(); 
    UpdateModel(fvm); 
    FillData(fvm, DateTime.Parse(DateTime.Now.Year.ToString() + " " + fvm.SelectedMonth + " 01")); 
    return View(fvm); 
} 

這是在後的代碼後面,你可以抓住從FVM所選擇的值,然後在你的選擇列表中的項目嫁給那個值了。

此代碼直接從我的代碼中解除,因此可能需要修改以適應您的情況。

這是否有意義?

0

你試過的一些代碼在這裏會很方便kurozakura。

同時,

如果您已將視圖綁定到模型,則可以使用UpdateModel將值返回。

所以,如果你綁定到一個名爲User的類然後;

User myUser = new User; 
TryUpdateModel(myUser); 

如果你還沒有綁定它,然後使用Eduardo的技術,並使用類似的東西;

public ActionResult MyViewsAction(FormCollection collection) 
{ 
    string a = collection["selectListCtrlname"]; 
} 
+0

以及我沒有使用FormCollection,但沒有運氣,因爲如果我這樣做只會返回存儲的字符串值,該值來自下拉列表的值,但我需要文本 – kurozakura 2009-08-27 03:48:21

+0

我不確定您想要什麼,除非您設置每個選項的值屬性也是文字。因此,一個選項可能看起來像<選項值=「這是選項的文本」>這是選項的文本,但我不知道你會得到多遠。還有一種方法,請參閱下一個答案。 – griegs 2009-08-27 03:53:42

2

下面的類使用反射來獲取列表中選定值的文本。不支持多個選定的列表項目。

using System.Web.Mvc; 

/// <summary> 
/// Provides a set of static methods for getting the text for the selected value within the list. 
/// </summary> 
public static class SelectListExtensions 
{ 
    /// <summary> 
    /// Gets the text for the selected value. 
    /// </summary> 
    /// <param name="list">The list.</param> 
    /// <returns></returns> 
    public static string GetSelectedText(this SelectList list) 
    { 
     foreach(var item in list.Items) 
     { 
      var dataValuePropertyInfo = item.GetType().GetProperty(list.DataValueField); 
      var itemValue = dataValuePropertyInfo.GetValue(item, null); 

      if(itemValue != null && itemValue.Equals(list.SelectedValue)) 
      { 
       var textValuePropertyInfo = item.GetType().GetProperty(list.DataTextField); 
       return textValuePropertyInfo.GetValue(item, null) as string; 
      } 
     } 

     return null; 
    } 
} 
相關問題