您的位置:首页 > 其它

【MVC】MVC中页面传值的几种方式总结

2016-06-05 18:08 435 查看
    原来写代码的时候都是别人写就照着写,大部分都是返回json,使用js,但是对于其他的传值方式用的少之又少,特别是当不使用easyUI的时候对它更是感觉到生疏,今天就对它的几种传值方式进行一下总结。

一、Controller-->View

1.ViewData

使用ViewData是采用键值对的形式,通过key值读取对应的value;ViewData只对当前Action有效。在View中会自动识别到拥有唯一键值的ViewData,并将数据显示出来。

控制器中代码:

<span style="font-family:KaiTi_GB2312;font-size:18px;">public ActionResult(string Type)
{
DataSet ds = BigNumberBLL.QueryMessage(Type);
ViewData['ds']=ds;
return View();
}</span>


视图中接收:
<span style="font-family:KaiTi_GB2312;font-size:18px;">@using System.Data;
@Model DataSet
<table class="Table">
<thead>
<tr>
</span><td>名称</td>
</span><td>集中数</td>
</span><td>权重下限</td>
</span><td>异常数</td>
</tr>
<thead>
<tbody>
@if(Model !=null && Model.Tables.Count >0)
<span style="white-space:pre">	</span>{
<span style="white-space:pre">		</span>foreach(DataRow dr in Model.Tables["dta"].Rows)
<span style="white-space:pre">		</span>{
<span style="white-space:pre">			</span><tr>
<span style="white-space:pre">				</span><td>@(dr["GROUP_NAME"]) </td>
<span style="white-space:pre">				</span><td>@(dr["SUM_WEIGHT_VALUE"])</td>
<span style="white-space:pre">				</span><td>@(dr["SUM_COLLECT_VALUE"])</td>
<span style="white-space:pre">				</span><td>@(dr["Count"]) </td>
<span style="white-space:pre">			</span></tr>
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}
</tbody>
</table></span>


2、ViewBag

允许自定义属性进行赋值,ViewBag.属性=属性值得方式进行传值,其实这里跟ViewData的使用原理类似。利用HtmlHelper创建TextBox时,使用名称与ViewBag中的一致, 就会自动实现值绑定

控制器中代码:

<span style="font-family:KaiTi_GB2312;font-size:18px;">public ActionResult Index()
{
ViewBag.name = "韦文文";
ViewBag.EnglishName = "Vivian";
return View();
}  </span>
视图中代码:
<span style="font-family:KaiTi_GB2312;font-size:18px;"><pre name="code" class="html" style="line-height: 30px;"><div>
@Html.TextBox("name")
@ViewBag.EnglishName
</div>  </span>





二、Action-->Action

前面两种传值方式都是在view和Controller之间进行数据传递,那么如果某一个业务需要用到后台的两个Action,并且需要再这两个Action之间进行数据传递,这时需要用到另一个概念TempData:获取要传递到视图的临时数据.使用时,需要注意TempData的生命周期,只在第一次请求Action时临时数据存在,之后自动变为NULL,具体的使用与ViewData相同,属于键值对的数据字典类。


TempData

    使用TempData和使用ViewData方法是一样的,不同的是它可用于在不同的Action之间传值。
<span style="font-family:KaiTi_GB2312;font-size:18px;">public class MVCController : Controller
{
public ActionResult Index1()
{
TempData["name"] = "韦文文";
return View();
}

public ActionResult Index2()
{
string strName = TempData["name"].ToString()
return View();
}  </span>


小结:

     mvc的这几种传值方式应该都写过,不过总体不是很熟悉,从一开始的学习到现在写代码,不断熟练应用,越来越清晰,真的是一个不断反复的过程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: