Rayshawn
Rayshawn

Reputation: 2617

Get Request MVC querystring

I am using ASP.NET MVC, I have a search form for user input. When the form is submitted, the data from the form is passed to my index action to return a View displaying the requested data.

Within my Index action method I use the data entered to update the view.

The user does not have to input all fields of the form so the data my action receives has parameter keys that are empty. But I just want the keys that have values in the url.

What I get, not desirable Example:

http://www.domain.com/searchresults?name=&age=&id=98787879

As you can see name and age have no values. If I get rid of those in the address bar the correct data is still display correctly which is expected.

The url I want is just

http://www.domain.com/searchresults?id=98787879

Is there a way to parse the query string before is goes into the action method. Maybe using Ajax to truncate the unnecessary keys? But then how could I submit that and go to the page?

Upvotes: 0

Views: 366

Answers (2)

Ameen
Ameen

Reputation: 2586

You can do this via javascript but constructing the query string (I'm assuming the type of the form is GET) is the job of the browser and I would not interfere with it or get into the trouble of making sure your javascript works on all browsers.

Even though less efficient, I would just use a this.RedirectToAction call in your MVC controller and redirect the request to an overload of the method where the parameters are not defined (i.e. the url has only the parameters that have values). This way, the user's browser will have an extra round-trip because it will first receive a redirect response from your controller, but you would not need to deal with javascript on the client end.

Upvotes: 1

FosterZ
FosterZ

Reputation: 3911

in that case, you can first call up a javascript function on your search button click that will construct query string and url and fire to your specified Action

Upvotes: 1

Related Questions