使用Ajax.ActionLink更新下拉列表

时间:2010-11-27 16:30:25

标签: asp.net-mvc

我正在尝试更新下拉列表:

查看:

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

控制器:

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

        return Json(new SelectList(names));
    }

流程如下:当用户发出第一个请求时,列表从viewdata更新,然后用户按下刷新,并在ajax请求中填充下拉列表。

我尝试返回两个JSON结果 - 下拉列表未更新。返回SelectList时,下拉列表将被清除。

我该如何完成这项任务?

2 个答案:

答案 0 :(得分:1)

您可以将此下拉列入部分(Names.ascx):

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

然后在主视图中使用此编辑器模板:

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

你的控制器动作可能如下所示:

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);
}

答案 1 :(得分:0)

再次更新viewdata,以便视图可以使用相同的代码为第二个镜头更新自己,即Ajax返回。你不需要使用Json。让我知道它是怎么回事。