MVC传递数据的方式

用MVC方式编写程序时一般不使用服务器端控件,没有像webform写一个Button的事件时只需要 <asp:Button ID="bt1" runat="server" OnClick="bt1_OnClick" />,声明button的事件就可以了。

    那么MVC怎么提交数据的那 ?用传统的提交表单的方式提交数据。

1、post提交表单的方式

下面例子说明如何把用户名和密码提交到服务器端的

view代码
<% using(Html.BeginForm("index","test", FormMethod.Post)){ %>
  
<p> <%=ViewData["user"%> </p>
  
<fieldset>
  
<legend>用户提交</legend>
  
<p>用户名:<%=Html.TextBox("userName"%></p> 
  
<p>密 码:<%=Html.TextBox("passWord"%></p> 
  
<p><input type="submit" value="提交" /> </p>
</fieldset>
<% } %>

在view代码中BeginForm函数有几个参数BeginForm("index", "test", FormMethod.Post),index是actionName,test是Controller名字,formMethon是个枚举的提交方式。ViewData["user"] 把提交的数据展示出来。

Contoller代码
        [AcceptVerbs( HttpVerbs.Post)]
        
public ActionResult Index(string username, string password)
        {
            
//参数方式
            ViewData["user"=   username+ password ; 
           
//webform取数据方式
           
// ViewData["user"] =  Request.Form["username"] + Request.Form["password"];
            return View();
        }

上面两种接受参数的方式一样的,只需要把参数名字和view代码中的控件id一致就可以了。

MVC还有一种比较先进的接受数据的方式——通过UpdateModel方式得到

 [AcceptVerbs( HttpVerbs.Post)]
 
public ActionResult Index(User model)
 {
    ViewData["user"= model.UserName + model.PassWord;  //属性名字和参数名一致
    return View();
 }

/////////

 [AcceptVerbs( HttpVerbs.Post)]
 
public ActionResult Index()
 { 
   User u = new User();
   UpdateModel(u, Request.QueryString.AllKeys);  
    

   ViewData["user"=u.UserName + u.PassWord;  //属性名字和参数名一致 

   return View();
 }

 

上面两种写法结果一样的,至于有什么区别我还没看明白 ^_^

 

 2、get获取url参数

 get方式获取值可以用传统方式Request.QueryString得到url值,也可以使用上面提到的参数方式和UpdateModel模型方式。

get获取值代码
        [AcceptVerbs(HttpVerbs.Get)]
        
public ActionResult Index(string username,string password)
        {
           
//1、参数方式
           ViewData["w"= username + password;

           
//2、model方式
           ViewData["w"= model.UserName + model.PassWord;

           
//3、webform方式  
           
// ViewData["w"] = Request.QueryString["username"] + Request.QueryString["password"]; 
 
            
return View();
        }

上面三种方式都能正确接到值,其实第一种和第二种方式一样,都是参数方式,只是第二种比较灵活而已。而对于前两种方式,如果view页面有对应的展示控件(id一致),会把结果直接展示出来。

 

3、 TempData传值

TempData可以在页面直接传值,和viewdata用法一样,只不过他是一次性的,再次刷新会丢失

 

 

 

posted @ 2009-12-26 22:08  卒子  阅读(7014)  评论(0编辑  收藏  举报