【问题标题】:Return Json of SelectList in asp.net mvc?在asp.net mvc中返回SelectList的Json?
【发布时间】:2013-09-04 09:46:48
【问题描述】:

如果有人可以就以下内容提供建议,我会很感激:

我在控制器中有我的 SelectList:

 SelectList sl = new SelectList(_unitOfWork.TraumaRepo.GetByType(type).ToList(), "Code", "Name");

通常我的 Json 返回简单的字符串:

  return Json(new[]{
                        new { value = "1", text = "item 1" },
                        new { value = "2", text = "item 2" }}, 
                        JsonRequestBehavior.AllowGet);

如何遍历此 SelectList 以将其数据值和数据文本字段作为 JsonResult 返回?如何在 Json() 中包含 foreach 或 linq?

在我的视图中,我将它附加到我的 DropDownList:

    $.each(data, function (value, i) {

                    ddl.append(
                            $('<option/>', {
                                value: i.value,
                                html: i.text
                            }));

                });

【问题讨论】:

  • 你试过Json(sl);
  • 我将如何将其键和值附加到 DropDownList 中?请看我的编辑
  • 谢谢,我找到了一种使用 Linq 的方法: var list = from l in sl select new { l.Value, l.Text };

标签: asp.net-mvc json jsonresult


【解决方案1】:

直接获取 JSON 序列化列表对象

  return Json(_unitOfWork.TraumaRepo.GetByType(type).ToList(), 
                        JsonRequestBehavior.AllowGet);

【讨论】:

    【解决方案2】:

    将 ActionResult 替换为 JsonResult 除了以下链接可能对您有所帮助

    http://www.prideparrot.com/blog/archive/2012/3/returning_data_view_from_controller_action

    一个更简单的 json 示例

    http://www.akhildeshpande.com/2011/08/simple-jquery-getjson-example-in-aspnet.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2013-05-26
      • 2023-03-18
      • 2011-01-16
      • 1970-01-01
      • 2012-05-07
      • 2014-11-09
      相关资源
      最近更新 更多