MVC入门学习笔记(三)

2.TempData[]字典:

   TempData[]是一个可以跨Action的传递,且只传递一次.

   1.在HomeController.cs中创建字典:

    public ActionResult Index()
        {
            TempData["strValue"] = "跨页面传值";//这里进行了字典定义
            Response.Redirect("/home/about");//跳转到about页中
            return View();
        }

   2.因为页面将跳转到about页,并希望该页接受到传值,所以定义应在About.aspx中:

    <%=TempData["strValue"]%>

   3.编译运行:

   

   4.我们已经可以看到我们传递的值了,但是刷新以后,将不会显示,因为该传值只能传递一次

3.ViewModel模型

     我们先看一个以类为值的传递:

   1.创建类Class1.cs:

   

  2.在类中我们创建两个属性:

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

namespace MvcDemo
{
    public class Class1
    {
        public int Id { get; set; }
        public string Name{get;set ;}
    }
}

 

3.因为我们要在Index.aspx中取得数据,所以我们在相应的HomeController.cs控制器中输入:

public ActionResult Index()
        {
            MvcDemo.Class1 user = new Class1();
            user.Id = 33;
            user.Name = "张三";
            ViewData["strValue"] = user;
            return View();
        }

4.在View页面Index.aspx中,我们取得数据:

  <%=(ViewData["strValue"] as MvcDemo.Class1).Name %>

5.编译项目:

  

在这里,我们已经看到我们传递过来的Name属性了,但是在这种方法中有一个非常不好的问题,我们每次都要进行一次对ViewData[]的as转换,有没有更方便的方法那??

现在我们对代码进行修改:

  1.我们在相应的HomeController.cs控制器中做如下修改:

  public ActionResult Index()
        {
            MvcDemo.Class1 user = new Class1();
            user.Id = 33;
            user.Name = "张三";
            return View(user);
        }

   在这里,我们直接将user作为参数传递到View()方法中。

  2.相应的,我们在View页面Index.aspx中,做如下修改:

    <%ViewData.Model.Name %>

     其中Model是ViewData的一个属性

  3,另外我们还要修改Index.aspx页面的属性(注意,VS2010中的.aspx页面下不存在.cs页面,只能用本方法,如果VS2008中,也可以将ViewPage泛型化大道这种目的):

     Inherits="System.Web.Mvc.ViewPage"

     为

     Inherits="System.Web.Mvc.ViewPage<MvcDemo.Class1>"

  4.编译运行,运行结果是一样的

   

页面传值已经介绍完毕,其中不免有疏漏错误,请指正,限于本人当前技术


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/mane_yao/archive/2010/07/07/5718242.aspx

posted @ 2010-09-18 11:43  Yao,Mane  阅读(1915)  评论(7编辑  收藏  举报