Markus
Markus

Reputation: 3627

Update drop down using Ajax.ActionLink

I am trying to update the dropdown list:

View:

<div class="editor-field">
                Names: <%: Html.DropDownList("names", (SelectList)ViewData["Names"]) %>
                <%:Ajax.ActionLink("Refresh", "GetNames", new AjaxOptions { UpdateTargetId = "names", HttpMethod = "GET" })%>
</div>

Controller:

    [HttpGet]
    public ActionResult GetNames()
    {
        List<String> names = this.GenerateNames();

        return Json(new SelectList(names));
    }

The flow is the following: when user makes the first request, the list is updated from viewdata, then user presses refresh and the dropdown is populated usin ajax request.

I tried to return both JSON result - the dropdown is not updated. When returning SelectList the dropdown just gets cleared.

How can I accomplish this task?

Upvotes: 1

Views: 1278

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could put this drop down into a partial (Names.ascx):

<%@ Control Language="C#" 
    Inherits="System.Web.Mvc.ViewUserControl<YourApp.Models.SomeViewModel>" %>
Names: <%: Html.DropDownList(x => x.SelectedName, Model.Names) %>

And then in your main view use this editor template:

<div class="editor-field">
    <span id="names"><% Html.RenderPartial("Names"); %></span>
    <%: Ajax.ActionLink("Refresh", "Names", 
        new AjaxOptions { UpdateTargetId = "names", HttpMethod = "GET" }) %>
</div>

And you controller action could look like this:

public ActionResult Names()
{
    var model = new SomeViewModel
    {
        // TODO: fetch the names from db:
        Names = new SelectList(new[] {
            new { Id = "1", Text = "name 1" },
            new { Id = "2", Text = "name 2" },
            new { Id = "3", Text = "name 3" },
        }, "Id", "Text")
    }
    return View(model);
}

Upvotes: 1

Erx_VB.NExT.Coder
Erx_VB.NExT.Coder

Reputation: 4856

Just update the viewdata again so the view can use the same code to update itself for the second shot, being the Ajax return. And u don't need to use Json for that. Let me know how it goes.

Upvotes: 0

Related Questions