tyson27
tyson27

Reputation: 11

Url.Action doesn't work in Controller?

the following code doesn't have error but it just doesn't work, this belong to an action name GetAction and i want a link to go to action ViewDetails(String id), all in HomeController:

String getaction = "";
getaction += "<a href=\"@Url.Action(\"ViewDetails\", \"Home\", new { id = \"ID01\"}, null)\">Click here</a>";
ViewBag.View = getaction;
return View();

in the View of GetAction: @Html.Raw(ViewBag.View)

I can see the link name "Click here", but when I click on it, error:

HTTP Error 404.0 - Not Found The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.

Upvotes: 1

Views: 1100

Answers (2)

Mohammad Akbari
Mohammad Akbari

Reputation: 4784

Html.Raw can not render string as you expected. that allow to output text containing html elements. you can use following code

var url = Url.Action("ViewDetails", "Home", new { id = "ID01"}, null);

var getaction = new TagBuilder("a");
getaction.MergeAttribute("href", url);
getaction.SetInnerText("Click here");

ViewBag.View = getaction;

Upvotes: 0

Daniel
Daniel

Reputation: 2804

You can't embed razor code like that, it will treat it like a literal. You may as well evaluate the URL right away, its doing the same thing the view would do.

String getaction = "";
getaction += "<a href=\""+UrlHelper.Action("ViewDetails", "Home", new { id = "ID01"}, null)+"\">Click here</a>";
ViewBag.View = getaction;
return View();

Upvotes: 1

Related Questions