MVC學習系列2--向Action方法傳遞參數

來源:互聯網
上載者:User

標籤:

首先,建立一個web項目,建立一個Home控制器,預設的代碼如下:

 public class HomeController : Controller    {        // GET: Home        public ActionResult Index()        {            return View();        }    }

現在我要向Index方法,傳遞一個參數,id,為了方便測試,適當的修改一下代碼

 public class HomeController : Controller    {        // GET: Home        public string Index(int? id)        {            return "ID=" + id;        }    }

然後運行程式,結果是。。。

 

在瀏覽器中輸入:Home/Index/200,就得到想要的結果了。也就是向action方法,傳遞了一個參數id,值為200.

 

上面是傳遞一個參數,然而,在實際工作中,我們會不止向控制器的Action方法,傳遞一個參數,那麼傳遞多個參數怎麼做呢???

 public class HomeController : Controller    {        // GET: Home        public string Index(int? id,string name,string sex)        {            return "ID=" + id+"<br/>"+ "Name="+name+"<br/>"+ "Sex="+sex;        }    }

這裡就是傳遞多個參數。

運行代碼,結果是:

 

在瀏覽器中輸入:Home/Index/10?name=孫權?SEX=人妖

注意:這裡在瀏覽器中輸入的參數:name,SEX要和控制器中的Action方法的參數名字要一樣,大小寫則無所謂。

 

顯然這不是我們想要的結果,怎麼做呢,一時想不到好辦法,我修改了一下路由:

 

  public static void RegisterRoutes(RouteCollection routes)        {            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");            routes.MapRoute(                name: "Default",                url: "{controller}/{action}/{id}/{name}/{sex}",                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional,name=UrlParameter.Optional,sex=UrlParameter.Optional }            );        }

 

然後這樣,就傳過來了:

傳遞多個參數的情況這樣做:

記錄一下

 

MVC學習系列2--向Action方法傳遞參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.