Action with a string array as parameter - asp.net-mvc

I want to call an action with something similar to this uri:
http://server/controller/action/?columns=firstname&columns=lastname&columns=age
and use it like this:
public ActionResult Action(string[] columns)
{
}
how do I do it?

Google is my friend ;)
http://server/controller/action/?columns[]=firstname&columns[]=lastname&columns[]=age
Edit:
Actually you just write as I did in my original question. The reason to why I didn't get it working in the first place is that I used "column" in the query string and "columns" in as action parameter.

I don't know if it's the difference between get and post parameters, but your original post works perfectly good with post parameters. In fact, when using []'s in post parameters the array becomes null in the action parameter. I found this out when jQuery 1.4 started adding []'s in json arrays when posting. See: http://www.dovetailsoftware.com/blogs/kmiller/archive/2010/02/24/jquery-1-4-breaks-asp-net-mvc-actions-with-array-parameters

Related

elegant way to redirect with array in GrailsParameterMap groovy

Is there any elegant way to redirect with the array in GrailsParameterMap?
When I type:
redirect(action: "XXX", params: params)
I get array which looks like [Ljava.lang.String;#596a40f1
EDIT: I have more precisely defined my question.
'params' are accessible by ALL controllers/Interceptors when redirecting. The one thing to keep in mind is that a redirect issues a NEW request/response so the headers can be different from the original request you got...99% of the time they will NOT BE! But this is something to keep in mind.
Also if, you need 'params' in spring filter, you just have to manually parse the request yourself.
But as 'params' are merely the request parameters, they are available to all components that have access to the request. :)
Hope that answers the question.
to pass an array of values into one parameter you have to convert this array to ArrayList
example:
//String.split() returns as array of strings
//as List - converts array to a List
params=[cId: "1,16,18".split(',') as List]
you could convert params.cId parameter to a List just before redirect
params.cId = params.cId as List
redirect(action: "XXX", params: params)

Overloading a route with dynamic http parts

I have one route like:
GET /latest/:repo/:artifact controllers.Find.findLatestArtifact(repo: String, artifact: String)
that works as a restful api for us. But now, I have a new view with an html form that need to send actions to that controller filling up the parameters with two html selects from the form.
I have tried adding another route like:
GET /latest controllers.Find.findLatestArtifact()
and overloading the controller method to read the http get parameters manually, but it does not like it.
Previously in the past I already asked here how to fill up parameters from a html form, in a controller that does not have 0 args:
Binding an html form action to a controller method that takes some parameters
and seems that it was not possible. Then, how do I workaround this, without having to rename the controller method?
EDIT:
I've provided an answer to your other question but the clean solution to this is unrelated.
You actually can overload the route with something like
GET /latest controllers.Find.findLatestArtifact()
GET /latest/:repo/:artifact controllers.Find.findLatestRepoArtifact(repo: String, artifact: String)
Make sure they are listed in the correct order. Obviously these will route to different methods (this is cleaner server side and more descriptive to what the method actually does), so in your code you would want a simple redirect or just return the result of the overloaded method:
public static Result findLatestArtifact(){
return findLatestRepoArtifact("DefaultRepo","DefaultArtifact");
}
public static Result findLatestRepoArtifact(String repo, String artifact){
... some code here ...
}
Or you could do it your other way (see other answer)

Previous GET parameters being unintentionally preserved in POST request

As of current I navigate to a view using a GET request, looking something like this:
/batches/install?Id=2&ScheduledDate=07.29%3A12
From there, I send a POST request using a form (where I include what data I wish to include in the request.
Furthermore I set the forms action to "Create" which is the action I wish to send the request to.
My issue is the fact that sending this request keeps the GET arguments in the POST url, making it look the following:
../batches/Create/2?ScheduledDate=07.29%3A12
I do not want this since:
1: it looks weird
2: it sends data I do not intend it to send in this request
3: if my model already has a property named "id" or "scheduledDate" the unintentional GET parameters will get bound to those properties.
How can I ignore the current GET parameters in my new POST request?
I just want to send the form POST data to the url:
../batches/create
(without any GET parameters)
How would this be done?
As requested, here is my POST form:
#using (var f = Html.Bootstrap().Begin(new Form("Create")))
{
//inputs omitted for brevity
#Html.Bootstrap().SubmitButton().Style(ButtonStyle.Success).Text("Create batch")
}
Note that I use the TwitterBootstrapMVC html helpers (https://www.twitterbootstrapmvc.com/), althought this really shouldn't matter.
As requested, to sum up:
I send a get request to : /batches/install?Id=2&ScheduledDate=07.29%3A12.
Through the returned view I send a POST request to: /batches/create.
However the previous get parameters get included in the POST request URL making the POST request query: /batches/Create/2?ScheduledDate=07.29%3A12 (which is NOT intended).
This is not a great Idea though, but will give you what you want.
[HttpPost]
public ActionResult Create() {
//do whatever you want with the values
return RedirectToAction("Create", "batches");
}
This is a "Feature" of MVC that was previously reported as a bug (issue 1346). As pointed out in the post, there are a few different workarounds for it:
Use named routes to ensure that only the route you want will get used to generate the URL (this is often a good practice, though it won't help in this particular scenario)
Specify all route parameters explicitly - even the values that you want to be empty. That is one way to solve this particular problem.
Instead of using Routing to generate the URLs, you can use Razor's ~/ syntax or call Url.Content("~/someurl") to ensure that no extra (or unexpected) processing will happen to the URL you're trying to generate.
For this particular scenario, you could just explicitly declare the parameters with an empty string inside of the Form.
#using (var f = Html.Bootstrap().Begin(new Form("Create").RouteValues(new { Id = "", ScheduledDate = "" })))
{
//inputs omitted for brevity
#Html.Bootstrap().SubmitButton().Style(ButtonStyle.Success).Text("Create batch")
}

How to pass array/list of parameters to mvc controller method

I have a controller method like that:
public async Task<IEnumerable<MyModel>> GetLinks(IList<string> links)
{
}
Is there anyway I can pass the params to that controller method form url like so:
<endpoint>/getginks?links=http://link1&?links=http://link2 etc?
but for some reason I cant even pass a single param <endpoint>/getginks?links=http://link1
In that case controller getting hit but links = null, I checked on debug.
is there anything I can do?
You need to add the array specification to the URL params, similar to if you were producing POST params from a view.
Try:
/getginks?links[0]=http://link1&links[1]=http://link2&links[2]=http://link3
You need to encode your string and then pass it to your controller.
you can use ajax call, before submitting just encode it
$.htmlEncode(links)
with the use of jquery.html.encode.decode.js

MVC - Query string and action parameter issue

I have an action method with the following signature,
ActionResult Search(string searchQuery)
This gets called from a partial view on button submit from a form. Problem is, please look at the 2 patterns below. When I submit my search key from my page it uses the following url (suppose search key is tool)
Search/?searchQuery=tool
But then if I click on a tool then,
Search/tool?searchQuery=garden
Now my method is reading tool in the parameter instead of garden (which is expected of course). I presume this is to do with incorrect presentation of items from both the context of the item itself and that of search.
Is there a nice way of resolving this issue? I want to read the query string term and search for it from the main search context i.e. Search/?searchQuery=<term> no matter where I am.
To get the QueryString, in your controller you should write something like this:
var mystring =Request.QueryString["searchQuery"];
This will get the query string no matter where is placed in your url.
Rename the input to
ActionResult Search(string searchQuery)
The model binder will then deserialize the query string param to that input value. It will work for both route params and query string params.

Resources