【问题标题】:FormCollection not containing <select> control added in MVC RazorFormCollection 不包含在 MVC Razor 中添加的 <select> 控件
【发布时间】:2011-03-22 19:35:32
【问题描述】:

在我看来,我有一个通过 Ajax 调用填充的下拉列表。此下拉列表在表单内。然而在提交时,我在 formCollection 中看不到这个控件。

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

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

--查看--

    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)
    {        
        ....
        ....
    }

}

【问题讨论】:

  • Ajax 调用是否有效?即页面加载时是否填写表格?
  • 是的。我在 Select 元素中获取项目

标签: jquery asp.net-mvc-3 razor


【解决方案1】:

元素需要 name 属性才能在 POST 请求中发回,您必须像这样更改您的选择(也删除 runat="server"):

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

【讨论】:

    【解决方案2】:

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

    控制器

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

    在视图中...

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

    但在您的情况下,由于您使用 Ajax 加载选项,因此最好不要使用帮助程序。

    【讨论】:

      猜你喜欢
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      • 2016-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多