gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:53:36 24 4
gpt4 key购买 nike

如何使 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com