如何获取asp.net mvc中selectfield列表的datafieldtext或selectedtext的值?

时间:2009-08-27 02:34:35

标签: asp.net-mvc model-view-controller drop-down-menu html-helper selectlist

不使用javascript \ AJAX。

3 个答案:

答案 0 :(得分: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;
    }
}

答案 1 :(得分:0)

你尝试过的一些代码在这里很方便kurozakura。

同时;

如果您已将视图绑定到模型,则可以使用UpdateModel来获取值。

因此,如果你绑定到一个名为User的类,那么;

User myUser = new User;
TryUpdateModel(myUser);

如果你没有绑定它,那么使用Eduardo的技术并使用类似的东西

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

答案 2 :(得分: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中获取所选值,然后将该值与选择列表中的项目结合起来。

此代码直接从我的代码中提取,因此可能需要根据您的情况进行修改。

这有意义吗?