visual tutorial studio proyecto plantillas plantilla para net mvc bootstrap asp c# html asp.net-mvc razor asp.net-web-api

c# - tutorial - ASP.NEt MVC utilizando la API web para devolver una vista Razor



plantillas mvc bootstrap (3)

La base del enlace proporcionado por twoflower es hacer que sus manejadores creen y devuelvan una instancia de una implementación IHttpActionResult personalizada. A continuación se muestra un ejemplo simplificado:

public class TestHttpActionResult : IHttpActionResult { private readonly HttpRequestMessage _request; private readonly string _responseString; public TestHttpActionResult(HttpRequestMessage request, string responseString) { _request = request; _responseString = responseString; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = _request.CreateResponse(HttpStatusCode.Created); response.Content = new StringContent(_responseString); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); return Task.FromResult(response); } }

Cómo hacer que la vista sea devuelta por el controlador y generada por Razor obtenga los datos de la API. Quiero mantener la vista de la maquinilla de afeitar y usar la API. api

Controlador MVC

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

Controlador de api

public class ProductsController : ApiController { private ApplicationDbContext db = new ApplicationDbContext(); // GET api/Products public IEnumerable<Product> GetProducts() { return db.Products; } }

Modelo:

@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>


Lea here sobre cómo usar el motor de vista de Razor dentro de su controlador de API web. La parte interesante es usar el paquete RazorEngine NuGet para hacer el trabajo pesado.


Puede enviar una solicitud HTTP a su controlador de API web desde el controlador MVC de ASP.NET:

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

Además, si puede aprovechar las ventajas de .NET 4.5 async / await, se recomienda hacerlo para evitar el bloqueo de llamadas:

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