c# - ASP.NEt MVC 使用 Web API 返回 Razor View

标签 c# html asp.net-mvc razor asp.net-web-api

如何使 Controller 返回并由 Razor 生成的 View 从 api 获取数据我想保留 razor 引擎 View 并使用 api 原始的 mvc Controller 返回带有数据作为参数的 View ,现在我想要来自 api 的数据

MVC Controller

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

API Controller

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 Controller 中向您的 Web API Controller 发送 HTTP 请求:

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,强烈建议您这样做以避免阻塞调用:

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);
    }
}

关于c# - ASP.NEt MVC 使用 Web API 返回 Razor View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22146823/

相关文章:

c# - 双 ToString - 无科学记数法

html - 查看 HTML 代码而不是呈现的 HTML

mysql - 使用 LINQ 构建动态查询

c# - DataContext 始终返回 null 作为外键

asp.net-mvc - 将 View 呈现为 MVC 中的字符串,然后重定向——解决方法?

c# - DataContext 的异常

c# - 动态格式化的 TextBlock

c# - 如何找到是否存在于任何多边形区域内的点?

javascript - 动态插入表: last row not detected by JQuery

html - 如何在html canvas元素中的两个圆之间画线