简体   繁体   中英

Return JsonResult Data With MVC View in View Model

I currently use Knockout to dynamically load data once a page has loaded. I'm using Controller methods, like:

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

This is then called like (in 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.

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.

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.

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.

How can I achieve this?

You could JSON serialize your view model into a javascript variable:

@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. You will have access to all its properties and you don't need to be doing expensive AJAX requests. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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