2011-03-22 81 views
0

在我看来,我有一个下拉,我通过Ajax调用填充。此下拉列表位于表单内。然而,在提交时,我在formCollection中看不到这个控件。FormCollection不包含<select>控件添加在MVC Razor

还有一件事,或者当我尝试添加Html.DropDownList(“AccountId”)时,出现错误 - 没有包含'AccountId'键的'IEnumerable'类型的ViewData项目。

上市我的视图和控制器代码...

--View--

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

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

- 控制器 -

public ActionResult GetAccounts(string id) 
{ 
    return Json(GetAccounts(), JsonRequestBehavior.AllowGet); 
} 

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult GetNames(FormCollection formCollection) 
{ 
    if (("AccountId") != null) 
    {   
     .... 
     .... 
    } 

} 
+0

Ajax调用是否工作?即当页面加载时填充的表单是什么? – 2011-03-22 10:28:11

+0

是的。我在Select元素中获得项目 – Vijay 2011-03-22 10:51:49

回答

5

元素需要name属性被发送回POST请求,你必须改变你的选择像这样(也放弃runat =“server”):

<select id="AccountId" name="AccountId"></select> 
+1

简单但非常有效。万分感谢!!! – Vijay 2011-03-22 11:50:55

0

如果您使用HTML助手创建下拉列表,则需要IEnumerable才能获取选项。所以,在你的控制器,你可以做这样的事情......

控制器

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

,并在视图中......

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

,但在你的情况,因为你加载使用Ajax的选项,你最好不要使用助手。

相关问题