【问题标题】:using viewbag data with jquery json使用带有 jquery json 的 viewbag 数据
【发布时间】:2014-05-06 05:59:01
【问题描述】:

我想在 JavaScript 数组中使用我的 ViewBag。我关注using viewbag with jquery asp.net mvc 3,我认为下面的代码就是我要找的,

 @model MyViewModel

<script type="text/javascript">
   var model = @Html.Raw(Json.Encode(Model));
    // at this stage model is a javascript variable containing
    // your server side view model so you could manipulate it as you wish
   if(model.IsLocal)
   {
       alert("hello " + model.FirstName);
   }
</script>

但是这段代码导致Json.Encode出错,然后我添加System.Runtime.Serialization.Json,但它也导致Encode出错,说Encode没有方法,我已经包含Newtonsoft.Json,但仍然没有结果。

我的 ViewBag 数据 ::

 public ActionResult Dashboard() 
 {
    ViewBag.inc = (from inc in db.Incident select inc.Title).ToList();
    return View();
 }

我想在 JavaScript 数组 中使用这个 ViewBag.inc 数据

【问题讨论】:

  • 在您的脚本中没有看到任何 ViewBag.inc,您实际上想要做什么?你的 viewbag.inc 在哪里?给我们看看你的控制器怎么样?

标签: javascript jquery asp.net asp.net-mvc json


【解决方案1】:

正如您所说,您已经在引用 Newtonsoft Json.Net 库,您可以使用以下代码::

 var inc = '@Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.inc))';

 inc= JSON.parse(inc);

 $.each(inc, function(index, data) {
     //you next code
 });

【讨论】:

    【解决方案2】:

    您使用的 sn-p 不使用 ViewBag,而是使用 Model。无论如何,如果您想将对象的序列化打印到视图,并且您已经在引用 Newtonsoft Json.Net 库(如您所说),那么您可以执行以下操作:

    var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
    

    如果你想使用 ViewBag 中的项目,你可以这样做:

    var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.inc));
    

    【讨论】:

    • 我只删除最后一个;它工作得很好。谢谢
    【解决方案3】:

    ViewBag 可以使用 like -

    var mn =  @{@Html.Raw(Json.Encode(ViewBag.ViewBagProperty));}
    alert(mn.YourModelProperty);
    

    对于模型 -

    var mn =  @{@Html.Raw(Json.Encode(Model));}
    alert(mn.YourModelProperty);
    

    不需要NewtonSoft.Json,我们可以使用默认的System.Web.Helpers.Json

    更新:这里是完整的模型解决方案,同样的概念也可以用于 ViewBag -

    假设你有这个模型 -

    public class XhrViewModel
    {
        public string data1 { get; set; }
        public string data2 { get; set; }
    }
    

    然后在控制器动作中,您将按以下方式构建上述模型的列表 -

        public ActionResult GetData()
        {
            List<XhrViewModel> model = new List<XhrViewModel>();
            model.Add(new XhrViewModel() { data1 = "Rami", data2 = "Ramilu" });
            return View(model);
        }
    

    然后在视图上,你可以有这样的东西 -

    @model IEnumerable<Rami.Vemula.Dev.Mvc.Controllers.XhrViewModel>
    @{
        ViewBag.Title = "GetData";
    }
    
    <h2>GetData</h2>
    
    <script type="text/javascript">
        var mn =  @{@Html.Raw(Json.Encode(Model));}
        alert(mn[0].data1);
    </script>
    

    当你执行页面时 -

    【讨论】:

    • @user3587919 不,它对我有用。你能告诉我你到底在哪里出错了吗?
    猜你喜欢
    • 1970-01-01
    • 2012-04-07
    • 2017-06-08
    • 2018-03-26
    • 2011-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    相关资源
    最近更新 更多