【问题标题】:ASP.Net Html.DropDownList Selected Element not SelectedASP.Net Html.DropDownList 所选元素未选择
【发布时间】:2013-02-25 23:35:41
【问题描述】:

我有一个使用 ASP.Net MVC Beta 5 的站点,我刚刚将它升级到 ASP.Net MVC 1.0。我在使用下拉列表中的选定项目时遇到问题。

关注的人有类似的问题(Html.DropDownList in ASP.NET MVC RC (refresh) not pre-selecting item)但我没有答案(除了它可能是一个错误)

我的 Controller 方法如下所示:

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult View(Guid id)
{
    IntegrationLogic logic = new IntegrationLogic(new IntegrationLinq());
    CompanyLogic companyLogic = new CompanyLogic(new CompanyLinq());
    IntegrationContainer container = new IntegrationContainer();

    container.Sources = logic.GetImportSource(id);
    container.Companies = companyLogic.GetCompanies(); // Returns a IList<company>
    container.SourceActions = logic.GetAllSourceActions(); // Returns an IList<SourceAction>
    container.SinkActions = logic.GetAllSinkActions();
    container.SuccessActions = logic.GetAllSuccessActions();
    container.FailureActions = logic.GetAllFailureActions();
    container.Actions = logic.GetAllActions();
    container.Watchers = logic.GetAllWatcherActions();
    container.ChainActions = logic.GetAllChainActions();

    return View("View", container);
 }

视图是针对模型的强类型如下

public partial class View : ViewPage<IntegrationContainer> {}

视图模板中的问题区域是:

  <label for="Companies">Company: </label><%=Html.DropDownList("Companies",
                                                new SelectList(ViewData.Model.Companies, "id", "name", item.CompanyID))%>

我正在创建一个下拉列表,所选项目实际上从未被选中 - 这就是问题所在。 “item.CompanyID”是一个 Guid,“id”是一个 Guid,“name”是 IList 中提供的公司对象的字符串,该对象保存在 ViewData.Model.Companies 实例中。

这实际上是一个错误吗?- 我很难理解为什么它仍然存在于 ASP.Net MVC 中......如果我已经完成了这件事,我会非常高兴。

无论如何,建议的解决方法是什么?

谢谢

【问题讨论】:

    标签: asp.net-mvc drop-down-menu html-select


    【解决方案1】:

    事实证明,如果通过 Html.DropDownList 控件的名称与集合对象的名称相同,则会导致 ASP.Net MVC 出现问题。

    所以如果我更改以下代码:

    <label for="Companies">Company: </label><%=Html.DropDownList("Companies",
                                                    new SelectList(ViewData.Model.Companies, "id", "name", item.CompanyID))%>
    

    到:

    <label for="Companies">Company: </label><%=Html.DropDownList("company",
                                                    new SelectList(ViewData.Model.Companies, "id", "name", item.CompanyID))%>
    

    现在一切正常。这是因为模型上的集合名称是 Model.Companies .... bonkers ... 另请注意,将控件名称的大小写从“公司”更改为“公司”也不起作用(这使得感觉我想)。

    我可以更改模型,但由于大部分是使用 Linq-to-SQL 构建的,我认为更改 Html 元素的名称更容易。

    【讨论】:

    • 在搜索了关于 SO 的 6 个问题后,这是唯一有效的答案……谢谢!
    • 在这个问题上我一直在用头撞墙,非常感谢。
    • 谢谢,这在 Mvc3 中仍然是一个问题
    • 在将值发布到服务器时,您做了哪些工作来将这些值恢复到模型中?我为我的应用程序尝试了您的建议,但 MVC 无法将值绑定回模型。你是从 FormCollection 中得到它们的吗?
    • 这在 MVC 4 中仍然是一个问题! :(
    猜你喜欢
    • 1970-01-01
    • 2017-12-21
    • 2013-08-03
    • 1970-01-01
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多