Generate hyperlink in ASP.NET MVC 2 controller?
I've been scouring the web for a way to do this.
I want to generate a hyperlink to an action from my controller and put it in a string. I need to be able to define the label and give it html attributes. I can get Url.Action(...)
working but that method doesn't let me define the label on the link.
HtmlHelper.GenerateLink(...)
looks promising开发者_运维知识库 but I can't find any concrete examples on how to use it.
The link should look something like this:
<a href="/Application/Form?action=view&id=11">View</a>
Add this property to your base controller:
protected HtmlHelper Html
{
get
{
var viewContext = new ViewContext( ControllerContext, new WebFormView( Request.CurrentExecutionFilePath ),
new ViewDataDictionary(), new TempDataDictionary(), Response.Output )
{
RouteData = ControllerContext.RouteData
};
return new HtmlHelper( viewContext, new ViewPage() );
}
}
and then call it from anywhere:
var link = Html.ActionLink( "Click Me", "action" );
try this
string str = string.Concat("<a href=\"",ControllernameinVar,"/",ActionNameinVar,"?action=",view,"&id=",variable">View</a>"
and then pass this in ViewData and call it in view
<%= str%>
there are a few ways to do this - here are 2:
<a href="@Url.Action("actionName", "controllerName")">Link name here</a>
Html.ActionLink(article.Title,
"Login", // <-- Controller Name.
"Item", // <-- ActionMethod
new { id = "<arguments here" }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. You need this value
// otherwise you call the WRONG method ...
// (refer to comments, below).
)
there are other overloads of each available
Perhaps a little more information on why you would want to do this would be a little more helpful. If you return a string that contains HTML it will by default be HTML encoded and rendered useless on the client. If you have a custom view where this will be rendered why not build the link there using @Html.ActionLink?
I guess I am trying to figure out the benefit of doing it in the controller rather than the view...
精彩评论