明天的明天 永远的永远 未知的一切 我与你一起承担 ??

是非成败转头空 青山依旧在 几度夕阳红 。。。
  博客园  :: 首页  :: 管理

asp.net mvc各种传值方式大全

Posted on 2018-08-02 15:17  且行且思  阅读(775)  评论(0编辑  收藏  举报

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 inHtml.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.Postpublic ActionResult Index(u as User){if(u.UserName != "重典")     ViewData.ModelState.AddModelError("u","用户名错误");        if(u.Password != "123456")            ViewData.ModelState.AddModelError("u","密码错");        return View();}