Ajax.BeginForm UpdateTargetId doesn't work with DropDownList

Tyler picture Tyler · Oct 21, 2009 · Viewed 12.1k times · Source

Code:

<% using (Ajax.BeginForm("GetResourcesByProject", "CreateRequest", new AjaxOptions { UpdateTargetId = "ResourceListDiv"}))
{
 Response.Write(Html.DropDownList("SelectProject", Model.ProjectList, "Select Project", new { onchange = "this.form.submit();" }));
} %>

When I run the page I get the correct controller action to trigger with the right data in the form collection:

public ActionResult GetResourcesByProject(FormCollection formCollection)
{
    var resourceModels = (from project in POTSModel.ProjectList
                          where project.Id == Convert.ToInt32(formCollection["SelectProject"])
                          select project).First().Resources;

    return PartialView("ResourceList", resourceModels);
 }

It works fine from an Ajax.ActionLink like this:

<%= Ajax.ActionLink("Select", "GetResourcesByProject", "CreateRequest", new { projectId = item.Id }, new AjaxOptions { UpdateTargetId = "ResourceListDiv" })%>

When the post happens I'm navigated to a new page instead of staying on the existing page and updating the contents of the div.

Thanks.

Answer

queen3 picture queen3 · Oct 21, 2009

submit() probably don't trigger Ajax.BeginForm, and so it is processed as usual post. See this for example: Additional jQuery events submitting my Ajax.BeginForm. Alternatively add submit button (maybe hidden) and call its .click().