Action参数和ActionResult

一、Action

       1、Action参数: 普通参数、Model类、FormCollection

        (1)、普通参数 Index(string name,int age)   框架会自动把用户请求的QueryString 或者Post表单中的值根据参数名字映射对应参数的值,适用于查询参数比较少的情况。

        public ActionResult F3(string name, int age)
        {
            return Content("姓名:" + name + "年龄:" + age);
        }

        (2)、Model类: 这种类叫ViewModel

        public ActionResult Index(IndexModel model)
        {  
            return View(model);
        }

       (3)、 FormCollection ,采用fc["name"]这种方式访问,适用于表单元素不确定的情况,用的比较少。

        public ActionResult F2Show()
        {
            
            return View();
        }
        public ActionResult F2(FormCollection fc)
        {
            string name = fc["name"];
            string age = fc["age"];
            return Content("姓名:" + name + "年龄:" + age);
        }
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>F2Show</title>
</head>
<body>
    <form action="/Test/F2" method="post">
        <input type="text" name="name" />
        <input type="text" name="age" />
        <input type="submit" />
    </form>
</body>
</html>

         (4)  一部分是普通参数,一部分Model:

        public ActionResult Index(IndexModel model,string department)
        {  
            return Content(model.Num1+model.Num2+department);
        }

        (5) 添加默认值,默认值参数在最后

        public ActionResult F3(string name, int age=12)
        {
            return Content("姓名:" + name + "年龄:" + age);
        }

       2、 Action 方法不能重载,除了加上[HttpGet] 、[HttpPost] 标记

        [HttpGet]
        public ActionResult F4()
        {

            return View();
        }

        [HttpPost]
        public ActionResult F4(string name,int age)
        {

            return Content("姓名:" + name + "年龄:" + age);
        }
<body>
    <form action="~/Test/F4" method="post">
        <input type="text" name="name" />
        <input type="text" name="age" />
        <input type="submit" />
    </form>
</body>

猜你喜欢

转载自www.cnblogs.com/fuyouchen/p/9368875.html