How can i display data in a View

╄→гoц情女王★ 提交于 2020-03-04 19:35:49

问题


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.


回答1:


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>



回答2:


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



来源:https://stackoverflow.com/questions/60181286/how-can-i-display-data-in-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!