猿问

如何调用View方法并将参数传递给方法?

我在侧边栏中有一个类别列表。


@foreach (var item in Model) {

    <li><a href="~/Books/Category/@item.Title">@item.Title</a></li>

}

我想通过单击类别来显示该类别的产品。为此,我实现了方法 ViewCategory。


public ActionResult ViewCategory(string name) { ... }

但我不知道如何正确传递参数。我正在尝试写这样的东西,但我明白做错了什么......


@Html.Action("ViewCategory", "Books", new {Title=item.Title})

请帮帮我


更新


我有一个查看索引,以及一种显示我的产品列表的方法


    public ActionResult Index()

    {

        HttpResponseMessage response = WebApiClient.GetAsync("Books").Result;

        var booksList = response.Content.ReadAsAsync<IEnumerable<BookDto>>().Result;

        return View(booksList);

    }

选择类别时,我只需要显示属于该类别的产品。我用 PartialView 列出了类别


<ul>

@foreach (var item in Model) {

    @*<li><a href="~/Books/@item.Title"></a></li>*@

    @Html.Action("ViewCategory", "Books", new { name = item.Title })

}

为此,我编写了一个我尝试使用的方法而不是


    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");

    }

但现在我有 NullReferenceException ......


元芳怎么了
浏览 323回答 3
3回答

弑天下

您可以按如下方式使用它。@{ Html.RenderAction("ViewCategory", "Books",&nbsp;&nbsp; &nbsp; new {param1 = "value1", param2 = "value2" }); }

墨色风雨

只是改变@Html.Action("ViewCategory",&nbsp;"Books",&nbsp;new&nbsp;{Title=item.Title})到&nbsp;@Html.Action("ViewCategory",&nbsp;"Books",&nbsp;new&nbsp;{name&nbsp;=&nbsp;item.Title})

凤凰求蛊

您可以尝试使用@Html.Action("Controller","Name",&nbsp;new&nbsp;{&nbsp;name&nbsp;=&nbsp;item.Title&nbsp;})
随时随地看视频慕课网APP
我要回答