您的位置:首页 > 编程语言 > ASP

【转载】ASP.NET MVC中Controller与View之间的数据传递总结

2012-06-27 13:27 507 查看

在ASP.NET MVC中,经常会在Controller与View之间传递数据,因此,熟练、灵活的掌握这两层之间的数据传递方法就非常重要。本文从两个方面进行探讨:

Ø ControllerView传递数据

Ø ViewController传递数据

一、ControllerView传递数据



1. 使用ViewData传递数据



我们在Controller中定义如下:

ViewData[“Message”] = “Hello word!”;

然后在View中读取Controller中定义的ViewData数据,代码如下:

<% = Html.Encode(ViewData[“Message”]) %>

2. 使用TempData传递数据



我们在Controller中定义如下:

TempData[“Message”] = “Hello word!”;

然后在View中读取Controller中定义的TempData数据,代码如下:

<% = Html.Encode(TempData [“Message”]) %>

3. 使用Model传递数据



使用Model传递数据的时候,通常在创建View的时候我们会选择创建强类型View如下图所示:

使用UpdateModel()的代码例子

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
//Users user = userRepository.GetUser(id);
//user.UserName = Request.Form["UserName"];
//user.Password = Request.Form["Password"];
//user.Telephone = Request.Form["Telephone"];
//user.Address = Request.Form["Address"];
//上述方法有一点繁琐,特别是增加异常处理逻辑之后。一个更好的方法是使用Controller 基类的内置方法UpdateModel()。该方法支持使用传入的表单参数更新对象的属性,它使用反射机制来解析对象的属性名称,接着基于客户端传入的参数值自动赋值给对象相关属性。
Users user = userRepository.GetUser(id);
string[] allowedProperties = new[] { "UserName", "Password", "Telephone", "Address" };
UpdateModel(user, allowedProperties);
userRepository.Save();

return RedirectToAction("Details", new { id = user.ID });
}

复制代码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: