FormCollection不包含在MVC Razor中添加的控件

在我看来,我有一个下拉列表,我通过Ajax调用填写。 此下拉列表在表单内。 但是在提交时,我没有在formCollection中看到这个控件。

还有一件事,或者当我尝试添加Html.DropDownList(“AccountId”)时,我得到错误 – 没有类型为’IEnumerable’的ViewData项具有键’AccountId’。

列出我的视图和控制器代码……

– 视图 –

using (Html.BeginForm("GetNames", "Account", FormMethod.Post, new { id = "accountParameters" })) { .... ....  //This is not available in formcollection //Html.DropDownList("AccountId"); //This throws exception @:

} ... ... $(document).ready(function () { $.ajax({ url: '/Account/GetAccounts', type: "GET", success: function (result) { for (i = 0; i < result.length; i++) { $('#AccountId').append($('').val(result[i].accountId).html(result[i].name)); } } }); });

– 控制器 –

 public ActionResult GetAccounts(string id) { return Json(GetAccounts(), JsonRequestBehavior.AllowGet); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult GetNames(FormCollection formCollection) { if (("AccountId") != null) { .... .... } } 

元素需要在POST请求中发回的name属性,你必须像这样改变你的选择(同时删除runat =“server”):

  

如果您使用HTML帮助程序创建下拉列表,它需要一个IEnumerable来获取选项。 所以,在你的控制器中你可以做这样的事……

调节器

 public ActionResult SomeAction() { ViewBag.SelectListItems = new List(); //Stash your items in this list. } 

并在视图中……

 Html.DropDownList("AccountId", Viewbag.SelectListItems); 

但在你的情况下,既然你正在使用Ajax加载选项,那么最好不要使用帮助程序。