【问题标题】:How to set the .Selected property of an item in ASP.NET MVC SelectList using LINQ?如何使用 LINQ 在 ASP.NET MVC SelectList 中设置项目的 .Selected 属性?
【发布时间】:2011-11-30 05:05:29
【问题描述】:

我正在尝试在视图中的下拉列表的操作方法中填充 SelectList。下拉列表可以很好地显示在视图上,但 selected 属性没有使用以下代码显示:

public ActionResult Edit(int ID)
{
    var ctx = new NorthwindEntities();
    var product = ctx.Products.Where(p => p.ProductID == ID).SingleOrDefault();
    var selectList = new SelectList(ctx.Categories, "CategoryID", "CategoryName");
    selectList.Where(s => s.Value == product.CategoryID.ToString()).SingleOrDefault().Selected = true; 
    ViewData["CategoryID"] = selectList;
    return View(product); 
}

但是,将selectedValue 参数传递给SelectList 构造函数就可以完成这项工作:

var selectList = new SelectList(ctx.Categories, "CategoryID", "CategoryName", product.CategoryID.ToString());

我的猜测是 LINQ 表达式是问题或 SelectedItem 只能在 SelectList 构造函数中指定。有什么想法吗?

【问题讨论】:

  • 你是对的......使用你的第二个选项。
  • 莱尼尔是对的。您有一个解决方案,可以从您的代码块中消除 1 行代码。
  • @David 感谢您的澄清。这意味着必须在完成任何计算/决策以选择所选项目后实例化 SelectList。

标签: asp.net linq asp.net-mvc-2


【解决方案1】:

这个问题在这里回答

Set selected value in SelectList after instantiation

如果你仍然认为它是错误的,那么打破你的 linq 查询并检查你是否可以在列表中找到一个对象,然后执行 if( obj != null) { selected = true;}

但从我读到的内容,选择的属性只能在构造函数中设置。

在那个链接中是一个包装器/帮助器方法

public static string DropDownListEx(this HtmlHelper helper, string name, SelectList selectList, object selectedValue)
{
    return helper.DropDownList(name, new SelectList(selectList.Items, selectList.DataValueField, selectList.DataTextField, selectedValue));
}

这可能会帮助你

【讨论】:

  • 我确实尝试过分解 linq 查询并首先检查 NULL。但这也没有任何好处。目前,很清楚要选择哪个 SelectItem,应该在实例化 SelectList 之前提前确定。感谢您的帮助扩展建议,应该会派上用场。
猜你喜欢
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 2011-05-16
  • 2021-07-09
  • 1970-01-01
  • 2010-10-18
  • 1970-01-01
相关资源
最近更新 更多