Search code examples
asp.netmodel-view-controlleractionresult

Returning custom data along with actionresult from an action method


I am sure many people have had this question but I failed to get any results after searching the web and SO or the search keywords were different.

I am working on a new asp.net mvc web app where I get a plain template returned by the index action method on the controller. Later in the document.ready event handler I build the ui dynamically and append the dom elements to the blank template and this just works fine. My issue is I need 2 server calls here,

1) to get the view from the index action method

2) an ajax call inside the document.ready{} to get the data using which I build the ui.

I was wondering if there is any method using which I could pass back the data from the index action method along with the blank template view and use this data to create the ui inside the document.ready event handler. This will save that one additional hit to the server.

The reason for not using partial views is

1) we have some functionality already developed in jquery and

2) in my org people think making the functionality using razor and partial view will not be as flexible, for example building and raising customevent in js is a great feature that helps to keep the functionality loosely coupled from other features. (please correct if we are wrong)

Edit: I thought an example will explain this better,

Say I need to create a list of users, but the entire list and its functionality like checkboxes selection etc are built by a js module. So along with the blank view i want to pass the "users" object which is a class in my models currently.

Kindly suggest.


Solution

  • You have a couple of options:

    1) Server-side rendering:

    Putting the necessary data into the model would seem to be the obvious thing to do...that's what MVC models are for.

    During the building of the HTML your View code runs - so you can access the model values in Razor code, which you can use to build your view and influence the final HTML. So in this scenario you build your view using Razor, rather than constructing it using JS code. You can of course still use JS to change it after the page has loaded, but it would be downloaded into the browser with the HTML already in the desired starting state.

    2) Client-side rendering, but with necessary data pre-populated:

    If you'd rather stick with your existing client-side rendering code, you could use Razor to inject some ready-made JSON into the JavaScript, so it's effectively hard-coded into the page when it first runs, rather than having to fetch it from the server separately via AJAX.

    For example, if you have some object in C# which holds the data, you can serialise it to a JSON string and then use Razor to write that string into your JS in the correct place.