简体   繁体   English

从apicontroller传递值到asp.net mvc4中查看

[英]pass value from apicontroller to view in asp.net mvc4

I have list of data in my api controller. 我的api控制器中有数据列表。

I want to pass this data to view using something similar to viewbag. 我想使用类似于viewbag的东西传递此数据。

I know we cant use viewbag in apicontrller , So Is there any alternative for it. 我知道我们不能在apicontrller中使用viewbag,所以有没有替代方案。

Normally ApiControllers do not return views. 通常ApiControllers不返回视图。 They return models , or HttpResponseMessage for that matter. 他们返回models ,或HttpResponseMessage So you could simply have a view model that will contain the required property and then have your API action return this view model. 因此,您只需拥有一个包含所需属性的视图模型,然后让您的API操作返回此视图模型。

You are not supposed to tho that, the API controllers return only data (XML, Json, etc). 你不应该这样,API控制器只返回数据(XML,Json等)。 So you should have two controllers: 所以你应该有两个控制器:

  • System.Web.Http.ApiControlle Use this to return collections of data for example: System.Web.Http.ApiControlle用于返回数据集合,例如:

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

    Returns a list of companies in Json or XML not a view. 返回Json或XML中的公司列表而不是视图。

  • System.Web.Mvc.Controller use this one for returning HTML without data for example an HTML table without rows or client-side templates. System.Web.Mvc.Controller使用这个来返回没有数据的HTML,例如没有行或客户端模板的HTML表。

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). 我的想法是在客户端使用JavaScript进行渲染,有很多理由这样做,主要是你有两个完全分离的数据和表示,所以你可以重新使用你的数据Feed(例如在移动应用中)。

To render in the client-side is good idea to use some JavaScript rendering engine, take a look to http://handlebarsjs.com/ . 要在客户端进行渲染,最好使用一些JavaScript渲染引擎,看看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. 使用Jquery.getJSON()来获取您的JSON并从您的DOM或通过Ajax获取您的把手模板,选择一个DOM alement来插入生成的HTML。 Once you have the JSON, template and container use the function below: 获得JSON后,模板和容器使用以下函数:

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 :) 希望能帮助到你 :)

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

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