Tuesday, January 31, 2012

Send and Catch (Get) Query String in ASP.NET MVC



Hey, in this post i will share about sending and getting query string in ASP.NET MVC. It's very simple. First, create a controller method that accept parameter and make sure that the parameter’s name is same with the query string that you have defined. Here is the example.

   1: public ActionResult MyPage(string name, int age)
   2: {
   3:     string MyPageModel = "Hello.. I'm " + name + ". I'm " + age + " years old";
   4:     return View("MyPage", "_Layout", MyPageModel);
   5: }

And then, you can send the URL to this controller like below :

<a href="/Home/MyPage?name=Steve&age=20">Go To Steve's Page</a>

It’s very simple, isn’t it ?

In the example above, i create an <a/> (anchor) tag to make a link that refers to the controller method (MyPage). I give two data as query string (name and age). You can see that the query string in the link is like the standard query string. And in the controller method, i accept two parameters with same name (name and age). After that, you can process the data as you wish (In the example above, i create a sentence from the data that was obtained from query string and make it a model for the view).

One thing to remember, you must ensure that the query string variable name must exactly same with parameter in the controller. Otherwise, the query string won’t be obtained by the controller.

Thanks for visiting my blog. Hopefully it will be a useful post for you. Regards…

No comments:

Post a Comment