2016-11-15 14 views
0

我有一個DropDownListFor,它從控制器獲取數據源。有沒有辦法更新它,因爲我添加了新的值,然後我想要顯示在同一頁面上。更新DropDownListFor控制器MVC的數據源

查看:

@Html.DropDownListFor(m => m.Id, MyController.GetIds(Model.Id).Select(g => new SelectListItem { Text = g.Text, Value = g.Value }), @Resource.System_Choose, new 
        { 
         @class = "form-control selectpicker", 
         data_live_search = "true" 
        }) 

控制器:

public static List<SelectListItem> GetIds(int Id) 
    { 
     var retVal = new List<SelectListItem>(); 

     return retVal; 
    } 

回答

0

請與您的型號查看協議,具有List<SelectListItem>()類型的財產,並返回該屬性準備綁定和下拉顯示。

0

有一些方法來實現這一目標,

  1. 僅使用JavaScript來追加新的值來選擇選項。 (如果新值不發送到後端)
  2. Ajax並獲取新列表。

案例2的一個示例,我們可以將DropDownList放入partialview中,並使用ajax在partialview中獲取最新的DropDownList。

控制器:

public ActionResult QueryNewList() 
{ 
    return PartialView("~/Views/Home/_urPartialView.cshtml", viewModel); 
} 

HTML:

<div id="myDiv"></div> 

JS:

$.ajax({ 
     dataType: "html", 
     url: "QueryNewList", 
     success: function (html) { 
      $("#myDiv").html(""); 
      $("#myDiv").append(html); 
     } 
    })