简体   繁体   English

在视图模型中使用MVC视图返回JsonResult数据

[英]Return JsonResult Data With MVC View in View Model

I currently use Knockout to dynamically load data once a page has loaded. 我目前使用Knockout在页面加载后动态加载数据。 I'm using Controller methods, like: 我正在使用Controller方法,例如:

public JsonResult GetData(int paramId)
{
    return Json(new { Field1: true });
}

This is then called like (in JS): 然后称为(在JS中):

$.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: '/Dashboard/GetData',
        data: JSON.stringify({ paramId: valId }),
        dataType: "json",
        error: function (xhr, ajaxOptions, thrownError) {

        },
        success: function (data) {
            var val = data.Field1;
        }
    });

Here, the data object is an already JS accessible object. 在这里, data对象是一个已经可以通过JS访问的对象。

This approach is nice when I want to refresh individual items, but it makes the initial load fairly inefficient - there are a number of calls that need to be made to initialize the page. 当我要刷新单个项目时,此方法很好,但是它使初始加载效率很低-需要进行许多调用才能初始化页面。 In my ActionResult method to load the View, I'd like to call GetData() and return it's result in a way that matches the data value in the ajax call referenced above. 在要加载View的ActionResult方法中,我想调用GetData()并以与上面引用的ajax调用中的data值匹配的方式返回结果。

How can I achieve something like this? 我怎样才能实现这样的目标? I assume I'd need to add the result of the call to my model for the View, and then assign the value to a JS variable in the View. 我假设我需要将调用结果添加到View的模型中,然后将值分配给View中的JS变量。

Something like: 就像是:

public ActionResult Index() {
    var iModel = new IndexModel();
    iModel.DataResults = GetData();
    return View(iModel);
}

Then in the view itself, something like: 然后在视图本身中,如下所示:

var dataHolder = @Model.DataResults;

This doesn't work, I just get a naming of the type, not the actual data as it would exist in the data variable inside the ajax call. 这是行不通的,我只是得到类型的命名,而不是实际的数据,因为它存在于ajax调用内的data变量中。

How can I achieve this? 我该如何实现?

You could JSON serialize your view model into a javascript variable: 您可以JSON将视图模型序列化为javascript变量:

@model MyViewModel
<script type="text/javascript">
    var dataHolder = @Html.Raw(Json.Encode(Model));
    // At this stage you could use the dataHolder variable
    // that will contain all information about your view model
</script>

Now the dataHolder javascript variable will hold your entire view model that you passed to the view. 现在, dataHolder javascript变量将保存您传递给视图的整个视图模型。 You will have access to all its properties and you don't need to be doing expensive AJAX requests. 您将有权访问其所有属性,而无需执行昂贵的AJAX请求。 You will make those only when you want to get some fresh data from the server after the user makes some input, not on the initial page load. 仅当您希望在用户进行一些输入之后从服务器获取一些新数据时,而不是在初始页面加载时,才使用这些数据。 The whole purpose of SPAs is that your view could serve as many initial information as necessary under the form of a view model that you could JSON serialiize into a simple javascript variable. SPA的全部目的在于,您可以在JSON序列化为简单javascript变量的视图模型的形式下,根据需要提供尽可能多的初始信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM