asp.net mvc各种传值方式大全
MVC 各种传值方式 ViewData传值.
HomeController.cs Co
de:
{
ViewData["Title" ] = "Home Page" ;
ViewData["Message" ] = "Welcome to ASP.NET MVC!" ;
return View();
}
Views/Home/Index.aspx Code:
<p>
<%= Html.Encode(ViewData["Message" ]) %>
</p>
</asp:Content>
结果:在页面上显示Welcome to ASP.NET MVC!
示例二:
带参数传值.
URL Routing规则:
"Default" , // Route name
"{controller}/{action}/{param}" , // URL with parameters
new { controller = "Home" , action = "Index" , param = "" } //
Parameter defaults
);
HomeController.cs Code:
{
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:
<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¶str=world
显示: hello 520 world
访问:/home/index/hello
显示:hello (null) (null)
示例三:
强类型传值:
<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.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:
{
ViewData["Title" ] = "About Page" ;
return View(Space.Instance.GetSpace());
}
在About.aspx.cs后天修改如下.
About.aspx调用数据:
<ul>
<li><%=p.Name %>
<ul>
<%foreach (string r in p.Animal){ %>
<li><%=r%></li>
<%} %>
</ul>
</li>
</ul>
<%} %>
结果:

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
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);
}
<%=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(); %>
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();}
asp.net mvc各种传值方式大全的更多相关文章
- ASP.NET MVC程序传值方式:ViewData,ViewBag,TempData和Session
转载原地址 http://www.cnblogs.com/sunshineground/p/4350216.html 在ASP.NET MVC中,页面间Controller与View之间主要有以下几种 ...
- dotNET5的MVC页面传值方式总结
本文大致讲解mvc前后端的传值方式,包括control向view.view向control.以及action向action. 一.经典回顾 二.Controller向View传值 1. ViewBag ...
- asp.net页面间传值方式
使用asp.net开发项目,必然会在页面间进行传值,本文介绍几种常见的页面传值方式,仅作笔记,以便后续查找使用. 前提:新建两个页面:ValuePage.aspx,ObtainValue.aspx,本 ...
- ASP.NET MVC实现POST方式的Redirect
我们知道,在ASP.NET MVC中,要从一个Action跳转到另一个Action,通常是用一系列以“Redirect”开头的方法 Redirect RedirectToAction Redirect ...
- Asp.net页面间传值方式汇总
七种传值方式,分别是:URL传值,Session传值,Cookie传值,Server.Transfer传值,Application传值,利用某些控件的PostBackUrl属性和使用@Previous ...
- [转]ASP.NET MVC实现POST方式的Redirect
本文转自:http://www.cnblogs.com/ryuasuka/p/3604452.html?utm_source=tuicool 我们知道,在ASP.NET MVC中,要从一个Action ...
- asp.net mvc 页面传值的方法总结
转自:http://msprogrammer.serviciipeweb.ro/2012/01/15/usual-methods-to-transfer-data-from-page-to-page- ...
- Asp.Net MVC Filter 实现方式和作用范围控制
MVC中的Filte 简单又优雅的实现了AOP ,在日志,权限,缓存和异常处理等方面用的比较多.但本文不是讨论Filter这些功能点,而是总结Filter实现的方式.说实现也不太准确,也就是它的呈现方 ...
- Asp.net mvc页面传值-- dropdownlist
后台传值 List<ConfigParamInfo> paramList = configParamBLL.GetModelList(" and parentID=1" ...
随机推荐
- Xcode Archive打包失败问题
ionic3项目 完成 模拟器 真机测试均可以打包安装成功 在Archive的时候报错了 错误如下 code signing is required for product type 'Applic ...
- mbstowcs 和ifstream 前为何要setlocale
最近看公司的一些代码,发现一些地方调用了std::locale::global(locale("")); (c++) 和 setlocale(LC_ALL, "" ...
- java集合(一)
- js 音乐播放器
在写之前先说下我遇到得两个问题,第一个问题是,在音乐标签,我希望得是切换数据做到得,但是出了问题,暂时为解决,第二个问题,页面切换时音乐继续播放由卡顿情况,未处理好. 好了,那我们开始做这个音乐播放器 ...
- 简单搭个webapp开发框架
集成开发工具idea 服务器容器Tomcat 第三方依赖管理maven 暂时不集成 (spring+springmvc+mybatis(数据持久层存取)+dubbo+zookeeper(集群调度)) ...
- FUJI 富士 富仕 串口 N500I N700I 连接
本人丰富的硬件连接经验, 1.出售富士生化设备N500I, N700I 接入,C#代码demo, 可连接机器验证,验证后付款2. 提供宠物行业富士生化设备N500I, N700I型号接入软件技术支持 ...
- 最常用的JavaScript类的定义
混合的构造函数/原型方式 联合使用构造函数和原型方式,就可像用其他程序设计语言一样创建对象.这种概念非常简单,即用构造函数定义对象的所有非函数属性,用原型方式定义对象的函数属性(方法).结果是,所有函 ...
- WeX5学习笔记-02
1.安装wex5,下载地址 http://wex5.com WeX5是绿色免安装的,解压即可直接使用.注意:不能解压到含中文.空格和特殊字符 的目录下, 例如:Program Files,是不可以的, ...
- python安装代码包提示缺少 VC++ 14 控件的处理方式
下载如下文件,然后安装 http://go.microsoft.com/fwlink/?LinkId=691126
- C# 保存屏幕截图
//屏幕宽 int iWidth = Screen.PrimaryScreen.Bounds.Width; //屏幕高 int iHeight = Screen.PrimaryScreen.Bound ...