asp.net mvc框架之給Action參數賦值的方法


在開發過程過,幾乎上所有的地方都使用到了前端的請求,比如:get請求或者post請求。那么如果來獲取請求的參數呢?方法有三種。

 

方法一:使用模型類傳遞,Model

在前端傳遞過來的參數,必須要和模型類中的屬性名稱一致(可以不區分大小寫),因為框架的內部將模型類與參數進行了映射關系。

在Action方法中:

public ActionResult F1(Test3Model model)
        {
            return Content(model.id)
        }

Test3Model模型類:

public class Test3Model
    {
        public int id { get; set; }
        public string name { get; set; }
        public float height { get; set; }
        public bool sex { get; set; }
    }

前端傳遞過來的參數只能是Test3Model模型類中的屬性,比如參數只能是id,name,height,sex這些。

所以在Action方法中通過對象名.屬性來獲取

 

方法二:使用普通參數進行獲取請求的參數

public ActionResult F2(string name,int age)
{
       return Content("name="+name+"age="+age);
}

前端傳遞過來的參數必須是name和age參數,如果想輸入一個參數,可以將int改為int?

 

方法三:使用FormCollection獲取post方法提交的參數

public ActionResult F3(FormCollection fc)
        {
            string name = fc["name"];
            string age = fc["age"];
            return Content("name=" + name + ",age=" + age);
        }

 

方法四:使用[HttpPost]和[HttpGet]的使用

例子:登錄界面

[HttpGet]
        public ActionResult Baoming()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Baoming(BaomingModel model)
        {
            string result = "登錄成功!"+model.name;
            return Content(result);
        }

 

如果Action方法上面沒有[HttpPost]和[HttpGet]標簽時,get請求和post請求都要請求該方法,但是加上去以后,就會分別請求對應的方法。

 

方法五:HttpPostedFileBase類型上傳文件

public ActionResult UploadFile()
{
      return View();
}


 [HttpPost]
public ActionResult UploadFile(HttpPostedFileBase f1)
{
   f1.SaveAs(Server.MapPath("~/" + f1.FileName));
     return Content("上傳成功!");
}

 

前端:

<form action="/Baoming/UploadFile" method="post" enctype="multipart/form-data">
            <input type="file" name="f1"/>
            <input type="submit" value="提交"/>
        </form>

 

上傳的時候必須給表單添加enctype="multipart/form-data",上傳控件的name名稱與后端中的參數名稱一致


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM