Reputation: 159
How can i display data in views in asp.net core MVC?. In the Index.cshtml I have the following link to the detail page.
@Html.ActionLink("You_Controller_Name", "GetProductsDetail", new { id = item.ID }) |
I have this controller to get product by ID
public IActionResult Detail()
{
return View();
}
[HttpGet()]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
return view(product);
}
Need help on displaying Product information in the detail page.
Upvotes: 0
Views: 870
Reputation: 14228
You should do this in GetProductsDetail
Action
return View("Detail", product);
Read the following to have a better understanding
Updated
You can store like this in
@ViewBag.ProductName = product.ProductName
In View:
<h1>@ViewBag.ProductName</h1>
Full code
[HttpGet]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
@ViewBag.ProductName = product.ProductName
return View("Detail", product); // Make sure that in View is expecting `ProductList`, Otherwise, You just return View("Detail");
}
Calling another different view from the controller using ASP.NET MVC 4
Upvotes: 1
Reputation: 20116
You could also pass the ProductName
to Detail
action using RedirectToAction
,and then display it on view using ViewBag
.
Controller:
[HttpGet]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
return RedirectToAction("Detail", new { name = product.ProductName });
}
public IActionResult Detail(string name)
{
ViewBag.ProductName = name;
return View();
}
Detail View:
<h1>@ViewBag.ProductName</h1>
Upvotes: 1