0
我有這樣一個DropDownListFor:如何從jQuery中更改Razor DropDownListFor中的項目列表?
@Html.DropDownListFor(x => Model.SelectedStuff, Model.Placeholder, new { id = "targetList", @class = "form-control", style ="width:240px" })
Model.Placeholder開始了空,但在某些時候這個函數被調用,並需要得到重視targetList
這樣一個新的SelectList回來,它不會已經空了。
$.ajax(
{
url: '@Url.Action("GetNewList", "MyModels")',
type: 'POST',
dataType: 'json',
data:
{
someVal: _someVal
}
}
).done(
function (response) {
console.log(response);
$("#labelDirection").text(response.Data.Direction);
$('#targetList').??????? // want to attach response.Data.StuffForTargetList to targetList
}
返回的響應函數如下:
public ActionResult GetNewList(string someVal)
{
var db = new ApplicationDbContext();
var stuff = db.SomeTable.Where(t => t.Val > someVal);
var response = new veiwResponse()
{
Direction = "Up",
StuffForTargetList = stuff.Select(x => new SelectListItem()
{
Selected = false;
Text = x.Name,
Value = x.Val
});
};
return Json(response);
}
完美! (在函數中除了那個任性的'_') – davecove 2014-12-07 20:53:39
@davecove謝謝,錯過了錯字:) – 2014-12-07 20:57:50
生成一個帶有字符串連接的HTML標記是無效HTML和可能的XSS的最短途徑。請使用'$(「」).val(el.Value).prop(「selected」,el.Selected).text(el.Text)'。 – GSerg 2014-12-07 21:00:25