Follow a basic and robust example:
First create a Viewmodel, this is not mandatory but is good practice and in the future will realize the benefits of such.
namespace Exemplo.ViewModels
{
public class ProdutosViewModel {
public List<string> ListaProdutos { get; set; }
public ProdutosViewModel()
{
ListaProdutos = new List<string>();
}
}
}
Then in his Controller
, You query your API, populate the Viewmodel Products and return to View
namespace Exemplo.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
string ApiBaseUrl = "http://localhost:53568/"; // endereço da sua api
string MetodoPath = "Produtos/GetTodosProdutos"; //caminho do método a ser chamado
var model = new ProdutosViewModel();
try
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(ApiBaseUrl + MetodoPath);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var retorno = JsonConvert.DeserializeObject<List<string>>(streamReader.ReadToEnd());
if (retorno != null)
model.ListaProdutos = retorno;
}
}
catch (Exception e)
{
throw e;
}
return View(model);
}
}
}
Finally in his View
Index, you declare Products viewmodel as your @Model and display the list of products obtained from your API in the Controller. In your case as wanted to assemble a table with the name of the products, follows a very basic example even just to demonstrate
@model Exemplo.ViewModels.ProdutosViewModel
@{
Layout = null;
}
<div>
@if (Model.ListaProdutos != null && Model.ListaProdutos.Count > 0)
{
<table>
@foreach (var prod in Model.ListaProdutos)
{
<tr>
<td>@Html.Raw(prod)</td>
</tr>
}
</table>
}
</div>
You can use the c Httpclient class#.
– Maycon F. Castro
Hello Maycon gave a read, I understood what it is for, but you have some reference or Example for easy understanding ?
– Antonio_Sistema_de_Informacao
In this article you will see how to create Httpclient and take the result of the call: http://www.c-sharpcorner.com/article/consuming-asp-net-web-api-rest-service-in-asp-net-mvc-using-http-client/
– Maycon F. Castro
Take a look at this link on the part of the jqGrid component. link
– Waider Martins
what version of Asp.net and mvc you are using?
– Leandro Angelo