1. 程式人生 > >Action參數和ActionResult

Action參數和ActionResult

dev 不能重載 int index div bsp post 訪問 自動

一、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>

Action參數和ActionResult