I’m trying to generate an Html.ActionLink with the following viewmodel:
public class SearchModel
{
public string KeyWords {get;set;}
public IList<string> Categories {get;set;}
}
To generate my link I use the following call:
@Html.ActionLink("Index", "Search", Model)
Where Model is an instance of the SearchModel
The link generated is something like this:
http://www.test.com/search/index?keywords=bla&categories=System.Collections.Generic.List
Because it obviously is only calling the ToString method on every property.
What I would like to see generate is this:
http://www.test.com/search/index?keywords=bla&categories=Cat1&categories=Cat2
Is there any way I can achieve this by using Html.ActionLink
In MVC 3 you’re just out of luck because the route values are stored in a
RouteValueDictionarythat as the name implies uses aDictionaryinternally which makes it not possible to have multiple values associated to a single key. The route values should probably be stored in aNameValueCollectionto support the same behavior as the query string.However, if you can impose some constraints on the categories names and you’re able to support a query string in the format:
then you could theoretically plug it into
Html.ActionLinksince MVC usesTypeDescriptorwhich in turn is extensible at runtime. The following code is presented to demonstrate it’s possible, but I would not recommend it to be used, at least without further refactoring.Having said that, you would need to start by associating a custom type description provider:
The implementation for the provider and the custom descriptor that overrides the property descriptor for the
Categoriesproperty:Then we would need the custom property descriptor to be able to return a custom value in
GetValuewhich is called internally by MVC:And finally to prove that it works a sample application that mimics the MVC route values creation:
Damn, this is probably the longest answer I ever give here at SO.