ASP.NET MVC 前端(View)向后端(Controller)中传值

在MVC中,要把前端View中的值传递给后端Controller, 主要有两种方法

1. 利用Request.Form 或者 Request.QueryString

public ActionResult Index()    
{    
    ViewData["Message"] = "Welcome to ASP.NET MVC!";    
    ViewData["name"] = Request.Form["name"];    
    ViewData["sex"] = Request.Form["sex"];    
    return View();    
}   

 

2. 利用FormCollection来获取页面上的值

public ActionResult Index(FormCollection form)    
{    
    ViewData["Message"] = "Welcome to ASP.NET MVC!";    
    User u=new User();    
    u.Name = form["Name"];    
    u.Password = form["Password"];    
    return View(u);    
}    

 3)利用Action参数

<form name="form1" action="/Home/Index" method="post">    
    Name:<input type="text" name="name" /><br />    
    Sex: <input type="text" name="sex" />    
    <input type="submit" value="submit" />    
</form>    
<%    
    if (ViewData["name"] != null)    
    {    
        Response.Write("your name is:" + ViewData["name"] + ",  your sex is:" + ViewData["sex"]);    
    }               
%>    
:    
public ActionResult Index(string name, string sex)    
{    
    ViewData["Message"] = "Welcome to ASP.NET MVC!";    
    ViewData["name"] = name;    
    ViewData["sex"] = sex;    
    return View();    
}    

 

posted on 2016-10-13 12:21  新西兰程序员  阅读(3681)  评论(0编辑  收藏  举报