2
\$\begingroup\$

I need to pass an array of values in Url.Action.

Currently I'm doing:

var redirectUrl = Url.Action("search", new {   
        q = criteria.Q,
        advanced = criteria.Advanced,
        salaryfrom = criteria.SalaryFrom,
        salaryto = criteria.SalaryTo,
    });

if (criteria.JobTypes != null)
    redirectUrl += criteria.JobTypes.Aggregate(string.Empty, (a, x) => a += "&jobTypes=" + x);

To give me something like:

/search?q=developer&advanced=false&salaryfrom=20000&salaryto=80000&jobTypes=Full%20Time&jobTypes=Contract

Is there a nicer/cleaner approach?

\$\endgroup\$

migrated from stackoverflow.com May 29 '12 at 18:36

This question came from our site for professional and enthusiast programmers.

  • \$\begingroup\$ If it is few 2-4, It is ok to pass in URL ,But you have lots of values, I would like to pass an ID and get the object again in the next action method. But in your case i guess it is the search criteria from a search form, This should be OK to do . \$\endgroup\$ – Shyju May 11 '12 at 13:11
  • \$\begingroup\$ As per @Cygal's answer, the main reason we include the criteria in the URL is so that search results are GETable. So when someone POSTs a search, all we do is form the URL based on their input and redirect to our GET action. \$\endgroup\$ – Ben May 30 '12 at 8:42
  • \$\begingroup\$ see: stackoverflow:asp-net-mvc-routedata-and-arrays \$\endgroup\$ – Bill Barry May 30 '12 at 14:08
1
\$\begingroup\$
  • Concerning the comment you got about passing an ID, note that it's better to put search parameters in the URL, since it allows users to link to that search and refresh the page without having issues. All search engines do that.
  • Make sure to test for null without using type coercion: if(criteria.JobTypes !== null). It's a best practice that will avoid you a few surprises.
  • As for passing an array of values, I don't know much about ASP.NET but it looks like you can pass an array of values with Html.ActionLink. I don't know what version you're using but this seems specific to ASP.NET MVC 2.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.