\$\begingroup\$
\$\endgroup\$
3
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
-
\$\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– Shyju2012年05月11日 13:11:47 +00:00Commented 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\$Ben– Ben2012年05月30日 08:42:49 +00:00Commented May 30, 2012 at 8:42
-
\$\begingroup\$ see: stackoverflow:asp-net-mvc-routedata-and-arrays \$\endgroup\$Bill Barry– Bill Barry2012年05月30日 14:08:39 +00:00Commented May 30, 2012 at 14:08
1 Answer 1
\$\begingroup\$
\$\endgroup\$
- 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
lang-cs