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

Vij*_*jay 0 jquery razor asp.net-mvc-3

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

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

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

- 视图 -

    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>
Run Code Online (Sandbox Code Playgroud)

- 控制器 -

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

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

}
Run Code Online (Sandbox Code Playgroud)

tpe*_*zek 5

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

<select id="AccountId" name="AccountId"></select>
Run Code Online (Sandbox Code Playgroud)