【问题标题】:Return a view from controller with a JSON string in ASP.NET MVC在 ASP.NET MVC 中使用 JSON 字符串从控制器返回视图
【发布时间】:2017-01-14 17:10:00
【问题描述】:

我是 ASP.NET MVC 的新手。在我的应用程序中进行用户身份验证后,我将重定向到controller/action。在该操作中,我从服务中获取了一些 json 数据。

我想将该字符串数据传递给视图,然后使用 javascript 操作 json。注意:我说的是字符串,而不是模型。在网络表单中,

我通常会有一个页面范围的字符串变量,例如:string _json。然后我会将该 var 设置为我的服务返回的 json。然后在我的标记页面中,我会:

<script>
    var data = <%_json%>;
    etc.. 
</script>

有没有办法在 ASP.NET MVC 中做到这一点?:

控制器

public async Task<ActionResult> Index()
{
    string data = await _myService.GetList();
    return View(model); //here I want my view to know about data
}

查看

<script>
   var json = @data //something like this?
</script>

【问题讨论】:

  • 为什么要传递字符串而不是模型?
  • 因为我希望客户端上的 json 作为 jquery 网格小部件的数据源。此外,此数据来自第 3 方 api 调用,因此它已经是一个字符串。我只需要将它传送到视图。我会尝试其他人的建议,看看它是否有效。谢谢
  • 将字符串解析为对象并将模型传递给视图(或在客户端使用JSON.parse())解析它
  • 当我在客户端需要这个完全有效的 json 字符串时,我为什么还要麻烦创建一个模型并反序列化它?
  • 你必须在某处反序列化/解析它 - string 本身对你没有用:)

标签: c# json asp.net-mvc


【解决方案1】:

将控制器代码更改为:

public async Task<JsonResult> Index()
{
    string data = await _myService.GetList();
    return Json(data, JsonRequestBehavior.AllowGet); 
}

【讨论】:

    【解决方案2】:

    将控制器代码更改为:

    public async Task<JsonResult> Index()
    {
      string data = await _myService.GetList();
      return Json(new
            {
                JsonData = data ,
                Status = true
            }, JsonRequestBehavior.AllowGet);
    }
    

    【讨论】:

      【解决方案3】:

      如果您的 GetList 方法返回正确的 json 字符串,则只需使用 ViewBag

      控制器

      public async Task<ActionResult> Index()
      {
          ViewBag.SomeData = await _myService.GetList();
          return View();
      }
      

      查看

      <script>
         var json = @ViewBag.SomeData ; 
      </script>
      

      在其他情况下,您应该实现另一种方法来生成正确的 json 字符串,例如 @Sarang 版本将返回正确的字符串。用法:

      <script>
         var json = @Html.Action("YourMethod", "YourController") ; 
      </script>
      

      【讨论】:

        【解决方案4】:

        这个也可以。模型作为字符串对象

        <script>
           var data = @Html.Raw(Model)
        </script>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-12-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-12
          相关资源
          最近更新 更多