FormCollection not containing <select> contr

2019-08-19 04:41发布

问题:

In my view, I have a dropdown which I fill via Ajax call. This dropdown is within the form. Yet on submit, I don't see this control in the formCollection.

One more thing, alternatively when I try to add Html.DropDownList("AccountId"), I get error - There is no ViewData item of type 'IEnumerable' that has the key 'AccountId'.

Listed my View and controller code...

--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>

-- Controller --

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

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

}

回答1:

Element needs name attribute to be send back in POST request, you have to change your select like this (also drop the runat="server"):

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


回答2:

If you use the HTML helper to create a drop down list, it needs an IEnumerable for it to get the options. So, in your controller you could do something like this...

Controller

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

and in the view...

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

but in your case, since you're loading the options with Ajax, you're better off not using the helper.