在Html.ActionLink()中创建动态链接文本和链接

本文关键字:链接 动态 文本 创建 Html ActionLink | 更新日期: 2023-09-27 18:17:59

我想创建' @Html.ActionLink(model。country, "Details", " country ")'作为下拉列表中的选项,因为稍后,使用不同的角色访问将看到不同的链接…

控制器

    public ActionResult Index()
    {
        CountryList = db.CountryListTable.Select(x => x.countryName).ToList();
        ViewBag.ctr = CountryList;
        return View();
    }
视图

    @foreach (var item in @ViewBag.ctr)
    {
            <span>@item</span>
            <span>
            @* @Html.ActionLink((string)@item, "Details", "Country"); *@ @* this part throw error due to null *@
            </span>
            <br />
    }

@item does not null…我不知道为什么它抛出空值与@html.ActionLink封装…

供参考,我使用。net framework 4.0和MVC4…

我很新的MVC n .net框架

在Html.ActionLink()中创建动态链接文本和链接

应该是这样的:Html.ActionLink("Details", "Country", new { country = @item })

或者像这样:

<a href="@Url.Action("Details", "Country", new { country = @item })">@item</a>

你得到null,因为你没有传递参数给你的动作方法

谢谢!第二种方法确实有效!

只是作为其他参考,我认为第一个不是,因为第一个参数需要是字符串…所以应该是:Html.ActionLink((string)item, "Details", "Country", new {Country = @item})

然而,我尝试了这个方法,但仍然抛出相同的错误…

实际上,我确实通过viewbag传递参数…或者这不是所谓的"传递参数",我不知道…但是当我改变这个@Html。Actionlink到@item,它做list of item…

感谢Arjit Mukherjee…