2015-05-21 34 views
1
public ActionResult ProductDrop() 
    { 
     var list = new List<DropDownListItem>(); 
     list.Add(new DropDownListItem { Text = "Short", Value = ((byte)Products.Short) }); 

    } 

HTML部分填寫MVC DropDownListFor用JSON

@Html.DropDownListFor(x => x.ProductType, new SelectList(Enumerable.Empty<SelectListItem>())) 

jQuery的部分

$.getJSON('@Url.Action("ProductDrop", "Home")', function (result) 

當你看到試圖從控制器JSON加載的DropDownList,但缺少的東西。我怎樣才能讓物品下拉?

回答

0

由於使用ASP.NET MVC,我會建議分開邏輯。 這是工作例如:

型號:

public class ItemsModel 
{ 
    private readonly List<DropDownListItem> _items; 

    public List<DropDownListItem> Items 
    { get { return _items; } } 

    public ItemsModel() 
    { 
     this._items = new List<DropDownListItem>(); 
    } 

    public void addItem(string text, byte value) 
    { 
     this._items.Add(new DropDownListItem { Text = text, Value = value }); 
    } 
} 

public class DropDownListItem 
{ 
    public string Text { get; set; } 
    public byte Value { get; set; } 
} 

控制器動作:

public ActionResult Index() 
    { 
     return View(); 
    } 


    [HttpGET] 
    public ActionResult ProductDrop() 
    { 
     ItemsModel model = new ItemsModel(); 
     model.addItem("Short", 0x24); 
     model.addItem("Long", 0x32); 
     return PartialView("ProductDrop", model); 
    } 

了兩種意見:

指數:

@{ 
ViewBag.Title = "Index"; 
} 

<h2>Index</h2> 

@section scripts 
{ 
    <script> 
     $(document).ready(function() { 
     $.ajax({ 
      url: "@Url.Action("ProductDrop")", 
      type: "GET", 
      datatype: "text", 
      traditional: true, 
      async: true, 
      cache: false 
     }).done(function(result) { 
      $(".ddlist").html(result); 
     }); 
     }); 

    </script> 
} 

<div class="ddlist"></div> 

和PartialVie女:

@model MvcApplication1.Models.ItemsModel 

@Html.DropDownListFor(m=>m.Items, new SelectList(Model.Items, "Value", "Text")) 

你能避免局部視圖,如果您使用的代碼,而不JQuery的

附:對不起,我沒有考慮到你想返回JSON。 在JSON的情況下,看看https://stackoverflow.com/a/5246804/4121714 但我不明白你爲什麼要使用助手與JSON(也許我錯了)。

2

首先,你需要更新你的控制器動作返回JSON:

public ActionResult ProductDrop() 
{ 
    var list = new List<DropDownListItem>(); 
    list.Add(new DropDownListItem { 
     Text = "Short", 
     Value = ((byte)Products.Short) 
    }); 

    return Json(list, JsonRequestBehavior.AllowGet)); 
} 

然後,你需要在你的jQuery代碼來創建回調將環比$.getJSON調用的結果和追加的選項到你選擇的元素。就像這樣:

$.getJSON('@Url.Action("ProductDrop", "Home")', function (result) { 
    var dropdown = $('#ProductType');   
    $.each(result, function() { 
     dropdown.append(
      $("<option></option>").text(this.Text).val(this.Value) 
     ); 
    }); 
}); 
+0

一個小改進 - 在'$ getJSON()'之前添加'var dropdown = $('#ProductType');並使用'dropdown.append(..);'所以元素被緩存(避免搜索DOM每次) –

+0

好點,@Stephen。我已經更新了代碼示例以結合您的建議,將下拉選擇移出循環。我將它留給用戶來決定是否需要在'$ .getJSON'調用之外完成 - 也就是說,如果這段代碼在其生命週期中被多次調用。 – Peter