13

我有一个使用 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 中......如果这是我所做的事情,我会非常高兴。

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

谢谢

4

1 回答 1

21

事实证明,如果通过 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 元素的名称更容易。

于 2009-07-31T08:04:28.897 回答