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名称与后端中的参数名称一致

posted @ 2019-06-11 00:31  black娃  阅读(1864)  评论(0编辑  收藏  举报