简体   繁体   中英

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.

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

I have a View Index, and a method in which I bring up a list of my products

    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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM