[英]How to call View method and pass parameter to method?
I have a list of categories in the Sidebar. 我在侧边栏中有一个类别列表。
@foreach (var item in Model) {
<li><a href="~/Books/Category/@item.Title">@item.Title</a></li>
}
And I want to display the products of this category by clicking on the category. 我想通过单击类别来显示该类别的产品。 To do this, I implemented the method ViewCategory.
为此,我实现了ViewCategory方法。
public ActionResult ViewCategory(string name) { ... }
But I do not know how to pass the parameter correctly. 但是我不知道如何正确传递参数。 I'm trying to write something like that, but I understand that doing something wrong ...
我正在尝试写类似的东西,但我知道做错了什么...
@Html.Action("ViewCategory", "Books", new {Title=item.Title})
Help me please 请帮帮我
UPDATE UPDATE
I have a View Index, and a method in which I bring up a list of my products 我有一个View Index,以及一种显示我的产品列表的方法
public ActionResult Index()
{
HttpResponseMessage response = WebApiClient.GetAsync("Books").Result;
var booksList = response.Content.ReadAsAsync<IEnumerable<BookDto>>().Result;
return View(booksList);
}
I need to display only products that belong to this category when choosing a category. 选择类别时,我只需要显示属于该类别的产品。 I list the categories with PartialView
我用PartialView列出了类别
<ul>
@foreach (var item in Model) {
@*<li><a href="~/Books/@item.Title"></a></li>*@
@Html.Action("ViewCategory", "Books", new { name = item.Title })
}
To do this, I wrote a method that I try to use instead of 为此,我编写了一种方法尝试代替
public ActionResult ViewCategory(string name)
{
HttpResponseMessage responseBooks = WebApiClient.GetAsync("Books").Result;
List<BookDto> booksList = responseBooks.Content.ReadAsAsync<IEnumerable<BookDto>>().Result.ToList();
for (int i = 0; i < booksList.Count; i++)
{
if (booksList[i].CategoryName != name)
{
booksList.Remove(booksList[i]);
}
}
return View("Category");
}
But now I have NullReferenceException... 但是现在我有NullReferenceException ...
Just change 只是改变
@Html.Action("ViewCategory", "Books", new {Title=item.Title})
to 至
@Html.Action("ViewCategory", "Books", new {name = item.Title})
You can use it as following. 您可以按以下方式使用它。
@{ Html.RenderAction("ViewCategory", "Books",
new {param1 = "value1", param2 = "value2" }); }
您可以尝试使用
@Html.Action("Controller","Name", new { name = item.Title })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.