1

有没有办法使用 ViewBag 值在视图中填充锚标记的href值?我想要做的是这样的:

看法:

<a href="<%= ViewBag.MyURL %>" title="My URL">"<%= ViewBag.MyURL %>"</a>

控制器:

    public ActionResult Index()
    {
        ViewBag.MyURL = "http://www.Google.com";
        return View();
    }

我该如何正确地做到这一点?

谢谢!

4

2 回答 2

5

这是使用 MVC 和 Razor 动态更新 href 锚标记的方法:

控制器(如果需要,也可以在视图中的代码块中设置):

ViewBag.MyURL = "http://www.Google.com";

看法:

<a href="@Html.Raw(Html.AttributeEncode(ViewBag.MyURL))" title="@Html.Raw(Html.AttributeEncode(ViewBag.MyURL))"> @Html.Raw(Html.AttributeEncode(ViewBag.MyURL))</a>
于 2012-10-25T14:22:33.837 回答
2

如果控制器中有以下内容:

ViewBag.myURL = "http://www.my-url.com";

然后在您的视图中:

@Html.Raw("<a href=\"" + ViewBag.MyURL + "\" title=\"" + ViewBag.MyURL + "\">" + ViewBag.MyURL + "</a>")

Html.Action 帮助器通常在发布到同一网站内的另一个控制器和/或操作时使用。Html.Raw 非常适合建立到外部网站的链接。

于 2012-10-24T04:12:04.260 回答