tags:

views:

77

answers:

1

I am going to be generating some hyperlinks on the fly driven from our database. So for example I go and get some information about a project, then based on the configuration information in that DB table (Which contains information like type of HTML fields to generate) I'll dynamically create Html controls from a custom control I create in MVC.

This brings me to the thought of hyperlinks. What if I have to dynamically generate a hyperlink here or there for certain products so that the form below the product on our View which is dynamically generated with my custom control now is simply an . How do I specify a controller/action on those instances when you're not going to use a Helper method and can't (Because you're creating these fields dynamically to your view) use something like or will not see something like Html.Actionlink because the fields are dynamically generated at runtime?

A: 

One solution I've used is to create a wrapper class that contains all of this information that you can then pass to a helper method:

public class RouteWrapper
{
    public string RouteName { get; set; }
    public object RouteValues { get; set; }
    public string LinkText { get; set; }
    /* Other Properties pertaining to your data */
}

Within the wrapper you would have methods defining the RouteName, and RouteValues properties. Alternatively, if you just need to vary between controller and action you could set it up that way. Although you could just pass the controller and action in the RouteValues and specify "Default" as the RouteName.

You would then really be able to do what you need straigt in the view (assuming the RouteWrapper class is the model, syntax may be slightly off but you'll get the idea):

<%= Html.RouteLink(Model.LinkText, Model.RouteName, Model.RouteValues) %>

Hope this helps.

EDIT:

Just re-read and saw you aren't using helpers.

Wherever you are generating the anchor tags, you can use the LinkText property for the inner HTML and there is a method in the Routing class that will help you generate a URL based on a route name and route values. I'll post some code in a little bit once I figure out how it would go.

EDIT AGAIN:

OK, so this would be the general method for generating the anchor tag:

public string GenerateAnchorTag(ViewContext context, RouteWrapper model)
{
    string url = RouteTable.Routes.GetVirtualPath(context, model.RouteName, new RouteValueDictionary(model.RouteValues));
    return String.Format("<a href=\"{0}\">{1}</a>", url, model.LinkText);
}

That's what I would try (you need to include System.Web.Routing and maybe System.Web.Mvc). For the context you would need to grab the request context somehow. I normally am doing this in a helper extension so the helper variable already has a context I can pass. If you aren't using helpers you'll have to figure out the best way to pass the RequestContext to the method.

dhulk