问题
ViewBag.htmml = "<li>" + "Html.ActionLink(" + "Home" + ", " + "Dashboard" + ", " + "User" + ")" + "</li>";
Above is my code, using which I am trying render an ActioLink
to my view. When the code runs, using the following code, I don't get an actionlink with name as Home, instead i get Html.ActionLink(Home, Dashboard, User)
in my <li>
part. How to get an ActionLink with what I am trying.
@Html.Raw(ViewBag.htmml)
回答1:
As @Stephen Muecke have mentioned, HTML needs to be generated in the View, not in the Controller.
However, if you insist on creating it in the Controller, you need to have an HtmlHelper
available for you to call the ActionLink
method. But, as the name suggests, HtmlHelper
is only available automatically for you in the View.
You can create one yourself manually (using a solution from this answer for example), but this is very inefficient and error-prone.
But, since you're only trying to generate an <a>
element, and you already are creating the elements yourself (like the <li>
element), you can simply do this (using the UrlHelper
that is available in the Controller as well):
ViewBag.htmml = "<li><a href=\"" +
Url.Action("Dashboard", "User") +
"\">Home</a></li>";
来源:https://stackoverflow.com/questions/28186731/how-to-render-actionlink-to-view-form-controller