zoukankan      html  css  js  c++  java
  • MVC学习系列2--向Action方法传递参数

    首先,新建一个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 }
                );
            }

    然后这样,就传过来了:

    传递多个参数的情况这样做:

    记录一下

  • 相关阅读:
    mmzrmo4delphi
    了解猫咪,和猫咪更好地相处
    无线分类
    压缩ASPX,替换ASPX多余的空格
    字符串编码转换Unicode>GB2312
    Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct bas
    ntext、text 和 image (TransactSQL)
    ICON资源
    一个简单的优酷视频链接探测与分享功能
    表单圆角大法(无JS无图片通杀所有浏览器)
  • 原文地址:https://www.cnblogs.com/caofangsheng/p/5668606.html
Copyright © 2011-2022 走看看