不使用 javascript\AJAX。
问问题
1210 次
3 回答
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;
}
}
于 2010-04-20T12:09:42.157 回答
0
您尝试过的一些代码在 kurozakura 会很方便。
同时;
如果您已将视图绑定到模型,则可以使用 UpdateModel 取回该值。
因此,如果您绑定到一个名为 User 的类,那么;
User myUser = new User;
TryUpdateModel(myUser);
如果你还没有绑定它,那么使用 Eduardo 的技术并使用类似的东西;
public ActionResult MyViewsAction(FormCollection collection)
{
string a = collection["selectListCtrlname"];
}
于 2009-08-27T03:21:43.833 回答
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 中获取选定的值,然后将该值与选择列表中的项目结合起来。
此代码直接从我的代码中提取,因此可能需要修改以适合您的情况。
这有意义吗?
于 2009-08-27T03:59:40.233 回答