asp.net mvc各種傳值方式大全


ViewData傳值.
HomeController.cs Co de:

public ActionResult Index()

     ViewData["Title" ] = "Home Page" ;
     ViewData["Message" ] = "Welcome to ASP.NET MVC!" ;
     return View();
}

Views/Home/Index.aspx Code:

<asp:Content ID= "indexContent" ContentPlaceHolderID="MainContent"runat="server" >
    <p>
    <%= Html.Encode(ViewData["Message" ]) %>
    </p>
</asp:Content>


結果:在頁面上顯示Welcome to ASP.NET MVC! 

示例二:
帶參數傳值.
URL Routing規則:

routes.MapRoute(
     "Default" ,                                              // Route name 
    "{controller}/{action}/{param}" ,                           // URL with parameters 
    new { controller = "Home" , action = "Index" , param = "" // Parameter defaults 
);

HomeController.cs Code:

public ActionResult Index(string param,int? paraInt,string paraStr)

    ViewData["Title" ] = "Home Page" ;
    ViewData["Message" ] = "Welcome to ASP.NET MVC!" ;
    ViewData["Param" ] = param;
    ViewData["ParaInt" ] = paraInt;
    ViewData["ParaStr" ] = paraStr;
    return View();
}

Views/Home/Index.aspx Code:

<asp:Content ID= "indexContent" ContentPlaceHolderID="MainContent"runat="server" >
    <p>
    <%= Html.Encode(ViewData["Message" ]) %>
    </p>
    <p>
    <%= Html.Encode(ViewData["Param" ]) %>
    </p>
    <p>
    <%= Html.Encode(ViewData["ParaInt" ] ?? (object )"(null)" )%>
    </p>
    <p>
    <%= Html.Encode(ViewData["ParaStr" ] ?? (object )"(null)" )%>
    </p>
</asp:Content>

結果:
訪問:/home/index/hello?paraint=520&parastr=world
顯示: hello 520 world
訪問:/home/index/hello
顯示:hello (null) (null)

示例三:
強類型傳值:

新建一個xml文件:
<?xml version="1.0" encoding="utf-8" ?> 
<root>
<item name="Sea" >
    <animal>Fish</animal>
    <animal>Shrimp</animal>
    <animal>Crab</animal>
</item>
<item name="Sky" >
    <animal>Bird</animal>
    <animal>Man</animal>
</item>
</root>

新建一個類讀取xml數據.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Web.Hosting;

namespace ViewData.Models

    public class Space 
    
        public string Name get ; set ; 
        public string [] Animal get ; set ; 
        private static Space space;
        public IEnumerable<Space> GetSpace()
        
            XDocument xml = XDocument.Load(HostingEnvironment.MapPath("~/App_Data/Space.xml"));
            IEnumerable<Space> results = from p in xml.Root.Elements("item")
                                         select new Space
                                         
                                             Name = p.Attribute("name" ).Value,
                                             Animal = p.Elements("animal" ).Select(r => r.Value).ToArray()
                                         } ;
            return results;
        
        public static Space Instance
        
            get 
            
                if (space == null )
                
                    space = new Space();
                
                return space;
            
        
    
}

在HomeController內添加Action:

public ActionResult About()

    ViewData["Title" ] = "About Page" ;

    return View(Space.Instance.GetSpace());
}

在About.aspx.cs后天修改如下.

public partial class About : ViewPage<IEnumerable<Space>>

About.aspx調用數據:

<% foreach (var p in ViewData.Model){ %>
<ul>
<li><%=p.Name %>
<ul>
<%foreach (string r in p.Animal){ %>
<li><%=r%></li>
<%} %>
</ul>
</li>
</ul>
<%} %>

結果:


示例四:
表單的值回傳給服務器.
新建一個UserM類:UserM.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ViewData.Models

    public class UserM 
    
        public string Name get ; set ; 
        public string Password get ; set ; 
        private static UserM user;
        
        public static UserM Instance 
        
            get 
            
                if (user == null )
                
                    user = new UserM();
                
                return user;
            
        
    
}

HomeControllers添加Action

[AcceptVerbs("GET")]  //GET調用 
public ActionResult Form()

    return View(UserM.Instance);


[ActionName("Form"), AcceptVerbs("POST")]//POST調用 
public ActionResult SaveForm()

    UpdateModel(UserM.Instance, new [] "Name" , "Password" } );
    return View(UserM.Instance);
}


Form.aspx.cs后台添加強類型引用
public partial class Form : ViewPage<UserM>


Form.aspx
<p>
<%=Html.Encode(ViewData.Model.Name) %><br />
<%=Html.Encode(ViewData.Model.Password) %>
</p>
    <%Html.BeginForm();%>
    Name:<%=Html.TextBox( "Name" )%>
    Password:<%=Html.Password("Password" ) %>
    <input type="submit" value ="Submit" />
    <%Html.EndForm(); %>
1: ViewData傳值方式
ViewData的生命周期和View相同, 只對當前View有效.
   ViewData["zd"] = dfdfd
2:TempData傳值方式
   可以跨Action傳遞
   TempData的數據至多只能經過一次Controller傳遞, 並且每個元素至多只能被訪問一次,
  
   例如一個用法為,拋出一個異常。跳轉到error頁面
public ActionResult Index3()
{
      TempData["tempIndex"] = "出錯了!";
      Response.Redirect("/home/error");
      return View();
}
3:QueryString傳值
1)也可以使用new{}來為form的action增加querystring
2)在controler里使用Request.QueryString["word"]獲取值
例如:
<li>
                <%= Html.ActionLink("Browse", "Browse", "User", new { word = "word1" }})%></li>
               
Controler頁面:
public ActionResult Browse(string word)
        {
            ViewData["word"] = Request.QueryString["word"];
            ViewData["word2"] = word;
            return View();
        }
4:Post傳值
例如:直接使用mehod=post
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <div>
     <form action="/User/AddRelease" method="post">
      <ul>
         <li>用戶名1:<input type="text" value="" name="UserName2"/></li>
         <li>密碼1: :<input type="text" value="" name="Password2"/></li>
      </ul>
      <input type="submit" value="添加" />
      </form>
</body>
</html>
例如2:也可以使用HtmlHelper.post方法
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title></title>
</head>
<body>
    <div>
     <% Html.BeginForm("AddRelease", "User", FormMethod.Post); %>
      <ul>   
         <li>用戶名: <%= Html.TextBox("UserName") %></li>
         <li>密碼: <%= Html.TextBox("Password") %></li>
      </ul>
       <% Html.EndForm(); %>
      <input type="submit" value="添加" />
</body>
</html>
Html.BeginForm
Html.EndForm
Html.TextBox

一 工程結構
4個程序集
Microsoft.Web.Mvc --一些可以使用的,不確定的程序包
System.Web.Mvc  --主程序庫
下面兩個列入3.5的Net框架了
System.Web.Abstractions --Request,Respose等5大對象、緩存,那些用於Asp.net Webfrom下使用的,這個使用裝飾者模式來使的過去的使用的類,和mvc下使用的類像兼容。
System.Web.Routing --
同是3.5的引用
System.Web.Extensions --Ajax控件
文件
App_Data 數據庫
Content  樣式,圖片,Js等
Controllers 控制器,可以改變名字,默認值
Models 模型
Views  視圖
二 基本工作流程
http://localhost:23797/home/index
home 是控制器
index 是Action
HomeController --> Index()
方法 return View(); 這個方法會默認訪問View文件夾下的Home->Index.aspx文件
方法 return View("about"); 訪問我們指定的頁面
更改了代碼,要重新生成一下,才會起作用
三 MVC架構
頁面請求-->Controller->Models(ORM)->數據庫
              |
    頁面 <--Views
四 ViewData傳值,本頁View傳遞
   Controller --> Views 之間通過 ViewData 來傳值。
   Controller中寫 ViewData["zd"] = "歡迎你!";
   View中 調用 <%= ViewData["zd"] %>
  
   另外也可以是復雜類型
   List<string> sl = new List<string>();
   sl.Add("重典");
   sl.Add("冰動力");
   ViewData["zd"] = sl;
   View中調用
   <% foreach(string str in ViewData["zd"] as List<string>){ %>
   <%= str %>
   <% } %>
   對aspx頁面,進行修改可以不編譯生成。
五 另外一種傳值方式TempData,可以跨頁面Action傳遞一次
   TempData["ddd"] = "哈哈";
   Response.Redirect("/home/about");
   頁面about中
   <%= TempData["ddd"] %>
   只保留一次值。
  
   用途:比如程序運行到一定地方,報錯誤拋出異常了,到一個異常處理頁面,把錯誤信息傳過去,專門處理一下。
六  ViewData的另外傳遞方式,類的傳遞
    定義一個類
    public class User
    {
public string Name {get;set;}
public int ID {get;set;}
    }
    在Controller中進行實例化
    User user = new User();
    user.ID = 1;
    user.Name = "安安";
   
    ViewData["user"] = user;
   
    在View中
    <%= (ViewData["user"] as User).Name %>
    還有一更方便的方法:
    把對象放在 return View(user); 傳遞出來
    頁面View
    首先修改一下頁面class 繼承
    比如:
    public partial class Index : ViewPage
    -->
    public partial class Index : ViewPage<User>
    然后再頁面中
    <%= ViewData.Model.Name %>
    
    只能傳遞一個引用類型。
    將一個對象,用泛型類型傳遞到頁面中。
七  新建頁面
    1. 新建一個Controller
       默認的Action是Index
       public ActionResult Index()
       {
           return View();
       }
     2. 新建一個View
        跟剛剛的Controller同名
八  重定向,Redirect
    Response.Redirect("/user/edit");
    //WebFrom版通常跳轉還是支持的
    新的return的MVC模式的跳轉
    return Redirect("/user/edit");//新的跳轉
    return RedirectToAction("edit");
    //同 控制器不同Action 跳轉
    return RedirectToAction("index","edit");
    //不同 控制器跳轉
九  Url Routing路由
    home/index
    能定位到-->home控制器 -->index Action
    在golab.cs中
八  filter 過濾器
    編碼解碼 數據壓縮服務設置協議 等等 都可以在這里做
    在Action發生之前發生之后 執行
    在View顯示之前顯示之后 執行
   
    新建一個類,起名加參數驗證filter(ParamFiter)
    filter要繼承過濾器的基類 System.Web.Mvc.ActionFilterAttribute
   
     重寫方法
     protected override void OnActionExecuted(ActionExecutiongContext filterContext)
{
   //Action運行之后
}
     protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
   //Action運行之前
   if(filterContext.HttpContext.Request.QueryString["k"] != "goo")
    {
throw new Exception("這有一個錯誤");
    }
}
     protected override void OnResultExecuted(ResultExecutedContext filterContext)
{
     //在View顯示之后
}
     protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
      //在View顯示之前
} filter過濾器怎么用 在Controller中的類上面加上 [ParamFilter] public class HomeControler : Controler 整個Controller上都會運用這個過濾器 也可以放在Controller中的某個Action上 [ParamFilter] public ActionResult Index() http://localhsot:23797/?k=go 就可以訪問了 九 Helper初體驗    HtmlHelper 用來原有的服務器控件,顯示數據的時候要借用Helper    UrlHelper 由於url路由的存在,Url具有不確定性    /home/index    /home/index.ashx    如果連接寫死的話,就要整體替換,用urlhelper就可以避免。        另外 Helper 只能在View頁面上用,不要再控制器上使用,這個是規定不是絕對。    HtmlHelper只要在View頁面用Html調用就可以了。    UrlHelper只要在View頁面用url    超鏈接    <%= Html.ActionLink("首頁","index","Home") %>    HtmlHelper可以顯示所有的表單元素,包含form都是用它來顯示    <%= Html.TextBox("category") %>    HtmlHelper還有一個特殊的方法,輸出編碼作用    <%= Html.Encode() %>       UrlHelper只是用於顯示URL的    <%= Url.Action("index","home") %> 顯示    <%= Url.Content("//dd") %> 把網站路徑轉化為URL顯示出來 十  QueryString傳值方式     url?key1=value&key2=value2     獲取的時候就是用     Request.QueryString["key1"]         在Controller中,     ViewDate["V"] = Request.QueryString["word"];     在View中     <%= ViewData["w"]%>     在傳值的調用頁面中     <%= Html.ActionLink("編輯頁","edit","user",new {word = "zhongdian"},new {@class="x"}) %>     最后一個屬性是擴展的a標簽的,這里給它一個樣式。     由於class是關鍵字,可以把Class(c大寫)避免,也可以加@前導符轉義。     生成的Html頁面代碼     <a href="/user/edit?word=zhongdian" class="x">編輯頁</a>     還有一個更簡單的方法:     在Controllers中改寫     public ActionResult Edit(string word)     //作為Action的參數 十一 表單提交Post      <form> 因為提交的URL也有不確定因素,所以用Helper生成。      創建form      <% using(Html.Form("user","edit",FormMethod.Post)) { %>       username:<%= Html.TextBox("Username") %>       <br/>       password:<%= Html.Password("Password") %>       <br/>       <%= Html.SubmitButton("","提交") %>       <% } %>       在Controller中接受Form表單的元素的值       string un = Request.Form["Username"];       string ps = Request.Form["Username"];       ViewData["w"] = un + ps;       在頁面View中       <%= ViewData["w"] %> 十二 比較好的傳值方式,UpdateModel      UpdateModel其實是Controller集下的一個方法,這個方法是將Post、get提交過來的相應的值存儲到一個對象。      UpdateModel();      定義類      public class User      {        public string Name {get;set;}        public string Password{get;set;}      }      在Controller中方法中如何寫      User u = new User(); //Model      UpdateModel(u,Request.Form.AllKeys);//get也可以      string un = u.Name;      string ps = u.Password;      ViewData["w"] = un + ps;      在頁面View中      <%= ViewData["w"] %> 十三 單選復選 更新       單選框      <%= Html.RadioButton("n1","man",false)%>性別      單選框列表      <%= foreash(string s in Html.RadioButtonList("ah",new[]{"音樂","書法"}) ) {%> <%= s %> <%}%>      復選框      <%= Html.CheckBox("c1")%> 復選      在Controller中如何接受傳過來的值      ViewData["show"] = Request.Form["n1"]; //修改n1 為 ah 就可以測試顯示列表      在頁面View中      <%= ViewData["show"] %>       在復選框的值有多個,而且name又是相同的話,可以用一個字符串數據接收它的值。     十四 表單驗證 <form action="" method="post"> <%= Html.ValidatiesMessage("u")%> <fieldset> <legend>提交用戶</legend> <p><label>用戶名</label> <%= Html.TextBox("u.UserName")%> </p> <p><label>密碼</label> <%= Html.TextBox("u.Password")%> </p> <input type="submit"/> </fieldset> </form> 后面Controller的代碼 HttpVerbs.Post public ActionResult Index(u as User) { if(u.UserName != "重典")      ViewData.ModelState.AddModelError("u","用戶名錯誤");         if(u.Password != "123456")             ViewData.ModelState.AddModelError("u","密碼錯");         return View(); }
 
原文:http://blog.csdn.net/deepwishly/article/details/9836599


免責聲明!

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



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