2010-11-27 46 views
1

我試圖更新的下拉列表:更新下拉使用Ajax.ActionLink

查看:

<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時,下拉列表被清除。

我該如何完成這項任務?

回答

0

只需再次更新viewdata,以便視圖可以使用相同的代碼更新自己的第二個鏡頭,即Ajax返回。你不需要爲此使用Json。讓我知道事情的後續。

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

這是一個不錯的建議,比上次更好,好的達林:)投票你:) – 2010-11-29 01:10:22