简体   繁体   中英

pass value from apicontroller to view in asp.net mvc4

I have list of data in my api controller.

I want to pass this data to view using something similar to viewbag.

I know we cant use viewbag in apicontrller , So Is there any alternative for it.

Normally ApiControllers do not return views. They return models , or HttpResponseMessage for that matter. So you could simply have a view model that will contain the required property and then have your API action return this view model.

You are not supposed to tho that, the API controllers return only data (XML, Json, etc). So you should have two controllers:

  • System.Web.Http.ApiControlle Use this to return collections of data for example:

     public List<Company> Get() { return this._companyService.GetCompanies(); } 

    Returns a list of companies in Json or XML not a view.

  • System.Web.Mvc.Controller use this one for returning HTML without data for example an HTML table without rows or client-side templates.

How to link the two? The idea is to render in the client-side with JavaScript, there is a good few reasons to do it this way, the main ones are that you have data and presentation in two completely separated feeds so you will be able to re-use your data feed (in mobile apps for example).

To render in the client-side is good idea to use some JavaScript rendering engine, take a look to http://handlebarsjs.com/ .

Use Jquery.getJSON() to get your JSON and get your handlebars template from your DOM or via Ajax, select a DOM alement to insert the generated HTML. Once you have the JSON, template and container use the function below:

function RenderJson (json,template,container) {
    var compiledTemplate = Handlebars.compile(template);
    var html = compiledTemplate(json);
    $(container).html(html); //set new content
}

I know it can seem like a more complicated process but it you try it you will see the advantages, you will be able for example to test your data feed and your data presentation separately.

Hope it helps :)

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