Minggu, 06 Oktober 2013

How to use QueryString in MVC

Introduction


If you want to pass control or variable value from one form to another form then we can use QueryString. ASP.NET MVC will automatically pass any query string or form post parameter name “name” to Index action method when its invoked. You have to read about HomeController from my previous post i.e.  how to create HomeController class in MVC Because in MVC  id is an optional parameter in RegisterRoutes method.

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }


This code is available in RouteConfig.cs file which resides in App_Start folder. If you want to pass queryString in URL then you should pass that in Index method.

public String Index(string id, string name)

Lets take a simple example to use QueryString parameter.

Step-1:Create a string parameter in Index method in homeController class

  public class HomeController : Controller
    {
        //
        // GET: /Home/


        public String Index(string id)
        {
            return "id=" + id;
        }
     
    }
Run your application and pass parameter in url such as
Now your output will come

How to use QueryString in MVC


Now again create another parameter to Index method

   public String Index(string id,string name)
        {
            return "id=" + id + "and name=" + name;
        }

Run your application with some parameter such as
Now your output will come.

How to use QueryString in MVC

Tidak ada komentar:

Posting Komentar