pass value from apicontroller to view in asp.net m

2019-08-29 06:14发布

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.

2条回答
\"骚年 ilove
2楼-- · 2019-08-29 06:27

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 :)

查看更多
Ridiculous、
3楼-- · 2019-08-29 06:40

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.

查看更多
登录 后发表回答