ASP.NEt MVC 使用 Web API 返回 Razor 视图 [英] ASP.NEt MVC using Web API to return a Razor view

查看:33
本文介绍了ASP.NEt MVC 使用 Web API 返回 Razor 视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让控制器返回并由Razor生成的View从api获取数据我想保留razor引擎视图并使用api原始 mvc 控制器以数据作为参数返回视图,现在我想要来自 api 的数据

How to make the View returned by the controller and generated by Razor get the data from the api i want to keep the razor engine view and use the api the original mvc controller returns the view with the data as parameter now i want the data from the api

MVC 控制器

public class ProductController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

API 控制器

public class ProductsController : ApiController
{
    private ApplicationDbContext db = new ApplicationDbContext();

    // GET api/Products
    public IEnumerable<Product> GetProducts()
    {
        return db.Products;
    }
}

型号:

@model IEnumerable<WebApplication2.Models.Product>

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
    <th>
        @Html.DisplayNameFor(model => model.Name)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Category)
    </th>
    <th>
        @Html.DisplayNameFor(model => model.Price)
    </th>
    <th></th>
</tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Category)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Price)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
        @Html.ActionLink("Details", "Details", new { id=item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id=item.Id })
    </td>
</tr>
}
</table>

推荐答案

您可以从 ASP.NET MVC 控制器内向您的 Web API 控制器发送 HTTP 请求:

You could send an HTTP request to your Web API controller from within the ASP.NET MVC controller:

public class ProductController : Controller
{
    public ActionResult Index()
    {
        var client = new HttpClient();
        var response = client.GetAsync("http://yourapi.com/api/products").Result;
        var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;
        return View(products);
    }
}

此外,如果您可以利用 .NET 4.5 async/await,强烈建议您这样做以避免阻塞调用:

Also if you can take advantage of the .NET 4.5 async/await it is strongly recommended to do so to avoid blocking calls:

public class ProductController : Controller
{
    public async Task<ActionResult> Index()
    {
        var client = new HttpClient();
        var response = await client.GetAsync("http://yourapi.com/api/products");
        var products = await response.Content.ReadAsAsync<IEnumerable<Product>>();
        return View(products);
    }
}

这篇关于ASP.NEt MVC 使用 Web API 返回 Razor 视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆