【发布时间】:2014-04-04 12:06:45
【问题描述】:
如何让控制器返回并由 Razor 生成的视图从 api 获取数据我想保留 razor 引擎视图并使用 api 原来的 mvc 控制器以数据作为参数返回视图,现在我想要来自 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>
【问题讨论】:
-
我正在一个项目中学习 Razor 中 M、V 和 C 的角色。我相信您标记为“模型:”的内容应该标记为视图。此示例中的模型只是控制器生成的 Models.Product 对象的列表。
标签: c# html asp.net-mvc razor asp.net-web-api