
Problem
The problem I had is that I had a search page, which went to a search results page that could be paginated. The paginator needs to know the search criteria used, so it can create a link on the page which calls for page x with the correct search criteria set.
I originally had code that looked like this in my view:
@Html.PageLinks(Model.PagingInfo, x => Url.Action("Search",
new
{
shortName = Model.SearchCriteria.ShortName,
soundsLike = Model.SearchCriteria.SoundsLike,
postCode = Model.SearchCriteria.PostCode,
policyNumber = Model.SearchCriteria.PolicyNumber,
previousVersions = Model.SearchCriteria.PreviousVersions,
page = x
}))
The search criteria class has a list of properties that can be searched for. The problem is, I didn’t want to have a list of all the properties in any views that use it, I wanted to be able to say:
@Html.PageLinks(Model.PagingInfo, x => Url.Action("Search",
new
{
searchCriteria = Model.SearchCriteria.ShortName,
page = x
}))
However this code does not work, as you can’t pass a complex object into Url.Action. Serialising this into a query string doesn’t work. I looked into how I could do this via fixing the serialisation problem, but chose a different approach in the end which is documented below.
One Solution
Url.Action can take an anonymous object, or it can take a RouteValueDictionary. So the first step was to put a ToRouteValueDictionary in my model. This wasn’t going to work for me, because my domain classes don’t access System.Web (or any data access routines for that matter, I use IOC).
So I decided on an extension method that used reflection to create a Dictionary, this only adds results if the value isn’t null, which means we don’t have lots of null querystring parameters in practice:
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace Ncs.Ida.Common.ExtensionMethods
{
public static class ToDictionaryExtensionMethod
{
public static IDictionary ToDictionary(this object source)
{
return source.ToDictionary
The view then is responsible for turning the Dictionary into a RouteValueDictionary
@Html.PageLinks(Model.PagingInfo, x =>
{
var dict = Model.SearchCriteria.ToDictionary();
var routeValueDictionary = new RouteValueDictionary(dict) { { "page", x } };
return Url.Action("Search", routeValueDictionary);
})
One Response to “Converting any object to a RouteValueDictionary so I don’t have to list properties in a MVC view”
Riya
Nice article, THANKS FOR SHARING