当前位置: 移动技术网 > IT编程>开发语言>.net > Asp.net MVC中Controller向View传值

Asp.net MVC中Controller向View传值

2018年01月31日  | 移动技术网IT编程  | 我要评论
一、使用Model 首先创建一个Model public class HelloModel { private string _name

一、使用Model

首先创建一个Model

public class HelloModel  
    {  
        private string _name;
	private string _text;   
        public string Name  
        {  
            get { return _name; }  
            set { _name = value; }  
        }           
        public string Text  
        {  
            get { return _text; }  
            set { _text = value; }  
        }  
    }  
然后创建强类型的View视图,在View视图中第一行写@model Test.Models.HelloModel代表这个View使用的Model为“Test.Models.HelloModel”
在View中读取Model中定义的数据,View中使用:@Html.Encode(Model.Name)
注:因为当字符串中带有空格或者<>浏览器曲解,就要加上Html.Encode进行Html编码的转换,以防出现一些不必要的错误。

二、使用ViewBag
ViewBag允许一个动态对象上定义任意属性,并在视图中访问

Controller:

public ViewResult Index()
{
	ViewBag.Message="Hello";
	ViewBag.Date=DateTime.Now;
	
	return View();
}
View中:

@{
	ViewBag.Title="Index";
}

The message is:@ViewBag.Message

The day is:@ViewBag.Date.DayOfWeek

三、使用ViewData

Controller:

public ViewResult Index()
{
	ViewData["Message"]="Hello";
	ViewData["Date"]=DateTime.Now;
	
	return View();
}
View中:

@{
	ViewBag.Title="Index";
}

The message is:@ViewData["Message"]

The day is:@ViewData["Date"].DayOfWeek


总结:

1. ViewData与TempData方式是弱类型的方式传递数据,而使用Model传递数据是强类型的方式。
2. ViewData与TempData是完全不同的数据类型,ViewData数据类型是ViewDataDictionary类的实例化对象,而TempData的数据类型是TempDataDictionary类的实例化对象。
TempData实际上保存在Session中,控制器每次执行请求时都会从Session中获取TempData数据并删除该Session。TempData数据只能在控制器中传递一次,其中的每个元素也只能被访问一次,访问之后会被自动删除。
ViewData只能在一个Action方法中进行设置,在相关的视图页面读取,只对当前视图有效。理论上,TempData应该可以在一个Action中设置,多个页面读取。但是,实际上TempData中的元素被访问一次以后就会被删除。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网