Reputation: 21304
Is there a way to populate an anchor tag's href
value in the View using a ViewBag value? What I want to be able to do is something like this:
View:
<a href="<%= ViewBag.MyURL %>" title="My URL">"<%= ViewBag.MyURL %>"</a>
Controller:
public ActionResult Index()
{
ViewBag.MyURL = "http://www.Google.com";
return View();
}
How do I go about doing this correctly?
Thanks!
Upvotes: 1
Views: 6725
Reputation: 21304
Here was the way this worked to dynamically update a href anchor tag using MVC and Razor:
Controller (this could also be set in a code block within the View if needed as well):
ViewBag.MyURL = "http://www.Google.com";
View:
<a href="@Html.Raw(Html.AttributeEncode(ViewBag.MyURL))" title="@Html.Raw(Html.AttributeEncode(ViewBag.MyURL))"> @Html.Raw(Html.AttributeEncode(ViewBag.MyURL))</a>
Upvotes: 5
Reputation: 378
If you have the following in the controller:
ViewBag.myURL = "http://www.my-url.com";
Then in the view you have:
@Html.Raw("<a href=\"" + ViewBag.MyURL + "\" title=\"" + ViewBag.MyURL + "\">" + ViewBag.MyURL + "</a>")
Html.Action helper is typically used when posting to another controller and/or action within the same web site. Html.Raw is good for building links to external websites.
Upvotes: 2