MVC通过JSON视图模型查看

MVC通过JSON视图模型查看

本文介绍了MVC通过JSON视图模型查看的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我使用各种 JsonResult 端点来填充JavaScript的视图模型MVC应用程序。

I have an MVC application that I'm using various JsonResult endpoints to populate the javascript ViewModel.

我一直在使用jQuery的几个Ajax请求来填充模型,但我想尽可能多的inital模型传递到服务器上的视图。

I have been using several jQuery Ajax requests to populate the model, but I'd like as much of the inital model to be passed to the view on the server.

的视图模型具有3-5件(取决于用户处于该应用程序):

The ViewModel has 3-5 pieces (depending on where the user is in the application):


  1. 基本的网页链接,这些不经常改变,可能是在整个用户会话
  2. 完全一样
  3. 用户通知。

  4. 的用户数据。

  5. (可选)可视数据

  6. (可选)杂项数据

我目前使用这种code先装入三个部分:

I'm currently using this code to load the first three pieces:

$(document).ready(function () {

    ko.applyBindings(viewModel);
    @Html.Raw(ViewBag.Script)

    // Piece 1.  Almost always the same thing
    postJSON('@Url.Action("HomeViewModelJson", "Home")', function (data) {

        if (data == null)
            return;

        for (var i in data.Tabs) {
            viewModel.tabs.push({ name: data.Tabs[i] });
        }

        for (var i in data.Buttons) {
            viewModel.metroButtons.push({ name: data.MetroButtons[i] });
        }

        for (var i in data.Ribbons) {
            viewModel.ribbons.push(data.Ribbons[i]);
        }
        ApplyButtonThemes();
    });
});


// Piece 2.  Changes constantly. OK as is
postJSON('@Url.Action("GetNotifications", "NotificationAsync")', function (nots) {
    viewModel.notifications.removeAll();

    ko.utils.arrayForEach(nots, function (item) {
        item.readNotification = function () {
            hub.markNotificationAsRead(this.Id);
            return true;
        };
        viewModel.notifications.push(item);
    });
});

// Piece 3. Changes but should also be loaded at startup
postJSON('@Url.Action("GetUser", "UserAsync")', function (user) {
    viewModel.user(koifyObject(user));
});


postJSON = function(url, data, callback) {
    if($.isFunction(data)) {
        callback = data;
        data = {};
    }
    $.ajax({
        'type': 'POST',
        'url': url,
        'contentType': 'application/json',
        'data': ko.toJSON(data),
        'dataType': 'json',
        'success': callback
    });
};

我试图做这样的事情,但我发现,通过使用 @ Html.Action(HomeViewModelJson,家)引起的HTTP头得到改变,就好像它是JSON整个页面发送

I tried doing something like this, but I'm finding that by using the @Html.Action("HomeViewModelJson", "Home") is causing the HTTP headers to get changed and the whole page is sent as if it were JSON

       (function (data) {

            if (data == null)
                return;

            for (var i in data.Tabs) {
                viewModel.tabs.push({ name: data.Tabs[i] });
            }

            for (var i in data.MetroButtons) {
                viewModel.metroButtons.push({ name: data.MetroButtons[i] });
            }

            for (var i in data.Ribbons) {
                viewModel.ribbons.push(data.Ribbons[i]);
            }
            ApplyMetroButtonThemes();
        })('@Html.Action("HomeViewModelJson", "Home")');

我想要做的是使用现有的 JsonResult 终端获取JSON数据到我的服务器端视图模型,之前的页面发送给用户。

What I'd like to do is use the existing JsonResult endpoints to get Json data into my ViewModel on the server side, before the page is sent to the user.

有没有可以让我做任何选项W / O重写我的控制器?

Are there any options that will allow me to do that w/o rewriting my controllers?

推荐答案

在渲染您使用视图模型,右边的主视图?在这个视图模型简单地返回视图之前填充你不想使用AJAX要获取的属性:

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);
}

例如,如果您有以下作用是用于Ajax请求:

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;

和则相应的视图中,你可以使用 Json.En code 方法将整个模型序列化为JSON字符串:

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>

这篇关于MVC通过JSON视图模型查看的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 21:57