DropDownList值和文本

时间:2015-08-16 18:04:39

标签: jquery asp.net ajax asp.net-mvc asp.net-ajax

我正在使用jquery填充ASP.NET MVC中的下拉列表

$(function () {
    $.getJSON('/GetFoo', function (result) {
        var ddl = $('#foo');
        ddl.empty();
        $(result).each(function () {
            $(document.createElement('option'))
                .attr('value', this.Id)
                .text(this.Text)
                .appendTo(ddl);
        });
    });
});

这是返回该进程中使用的JSON的控制器操作:

public ActionResult GetFoo()
{
    ViewBag.IdTable = new SelectList(db.Table, "IdTable", "Description");
        return Json(ViewBag.IdTable, JsonRequestBehavior.AllowGet);
}

以下是我的下拉列表如何进入我的观点:

@Html.DropDownListFor(model => model.IdTable,Enumerable.Empty<SelectListItem>(), "-- Loading Values --", new { id = "foo" })

为了澄清我正在做的事情,我想在选择列表选项而不是IdTable中显示描述。

在我验证下拉列表选项之前,一切正常。实际上,它会出现以下错误:

  

值[Choice]对于IdTable无效。

所以我猜选择列表选项的值设置为Description字段,而不是Id字段。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

试试这个:

public ActionResult GetFoo()
{
    return Json(db.Table.Select(x=> new { Id = x.IdTable, Text = x.Description}), 
        JsonRequestBehavior.AllowGet);
}
JS改变中的

.attr('value', this.Id)

.attr('value', this.Value)
相关问题