我想在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
没有方法,我已经包含{ {1}},但仍然没有结果。
我的ViewBag数据::
Newtonsoft.Json
我想在 JavaScript数组
中使用此 public ActionResult Dashboard()
{
ViewBag.inc = (from inc in db.Incident select inc.Title).ToList();
return View();
}
数据
答案 0 :(得分:2)
您使用的代码段不使用ViewBag,而是使用模型。无论如何,如果要将对象的序列化打印到视图中,并且您已经引用了Newtonsoft Json.Net库(正如您所说的那样),那么您可以执行以下操作:
var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));
如果您想使用ViewBag中的项目,您可以执行以下操作:
var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.inc));
答案 1 :(得分:2)
如您所说,您已经引用了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 :(得分:1)
您可以使用Like for ViewBag -
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 。
更新:以下是使用Model的完整解决方案,同样的概念也可以与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);
}
然后在View上,你可以有这样的东西 -
@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>
当你执行页面时 -