MVC pass JSON ViewModel to View

痞子三分冷 提交于 2019-12-04 06:57:34

When rendering the main view you are using a view model, right? In this view model simply populate the properties that you don't want to be fetched with AJAX before returning the view:

public ActionResult Index()
{
    MyViewModel model = ...
    model.Prop1 = ...
    model.Prop2 = ...
    return View(model);
}

for example if you have the following action that is used for the AJAX requests:

public JsonResult GetProp1()
{
    Property1ViewModel model = ...
    return Json(model, JsonRequestBehavior.AllowGet);
}

you could use it from the main action to populate individual properties:

model.Prop1 = (Property1ViewModel)GetProp1().Data;
model.Prop2 = (Property2ViewModel)GetProp2().Data;

and then inside the corresponding view you could use the Json.Encode method to serialize the entire model into a JSON string:

@model MyViewModel
<script type="text/javascript">
    var model = @Html.Raw(Json.Encode(Model));
    // You could use model.Prop1 and model.Prop2 here
</script>

or you could also serialize individual properties if you don't need all of them:

@model MyViewModel
<script type="text/javascript">
    var prop1 = @Html.Raw(Json.Encode(Model.Prop1));
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!