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?

Bill Barry
2,30614 silver badges18 bronze badges
asked May 11, 2012 at 13:07
\$\endgroup\$
3
  • \$\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\$ Commented May 11, 2012 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\$ Commented May 30, 2012 at 8:42
  • \$\begingroup\$ see: stackoverflow:asp-net-mvc-routedata-and-arrays \$\endgroup\$ Commented May 30, 2012 at 14:08

1 Answer 1

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.
answered May 30, 2012 at 7:59
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.