服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - ASP.NET教程 - ASP.NET中MVC传递数据的几种形式总结

ASP.NET中MVC传递数据的几种形式总结

2019-12-25 12:50蓝图 ASP.NET教程

这篇文章主要介绍了ASP.NET中MVC传递数据的几种形式,以实例形式较为详细的分析总结了MVC数据传递的相关技巧与注意事项,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了ASP.NET中MVC传递数据的几种形式。分享给大家供大家参考。具体如下:

在Asp.net mvc开发中,Controller需要向View提供Model,然后View将此Model渲染成HTML。这篇文章介绍三种由Controller向View传递数据的方式,实现一个DropDownList的显示。

第一种:ViewData

ViewData是一个Dictionary。使用非常简单,看下面代码:

?
1
2
3
4
5
6
public ActionResult ViewDataWay(int id)
{
 Book book =bookRepository.GetBook(id);
 ViewData["Countries"] = new SelectList(PhoneValidator.Countries, book.Country);
 return View(book);
}

在View中使用下面代码取值:

?
1
2
3
4
<div class="editor-field">
    <%= Html.DropDownList("Country", ViewData["Countries"] as SelectList) %>
    <%: Html.ValidationMessageFor(model => model.Country) %>
</div>

上面代码使用as将它转换成SelectList。

处理POST代码如下:

?
1
2
3
4
5
6
7
8
[HttpPost]
public ActionResult ViewDataWay(int id, FormCollection collection)
{
  Book book = bookRepository.GetBook(id);
  UpdateModel<Book>(book);
  bookRepository.Save(book);
  return RedirectToAction("Details", new { id=id});
}

第二种:ViewModel

使用ViewModel的方式,我们先创建一个BookViewModel,代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class BookViewModel
{
 public Book Book
 {
   get;
   set;
 }
 public SelectList Countries
 {
   get;
   set;
 }
 public BookViewModel(Book book)
 {
   Book = book;
  Countries = new SelectList(PhoneValidator.Countries,book.Country);
 }
}

在控制器的Aciton使用ViewModel存放数据的代码如下:

?
1
2
3
4
5
public ActionResult ViewModelWay(int id)
{
  Book book = bookRepository.GetBook(id);
  return View(new BookViewModel(book));
}

在View中,这种方式比第一种方式好在:它支持智能感应。

效果和第一种方式一样。

第三种:TempData

使用TempData和使用ViewData方法是一样的。

Action代码如下:

?
1
2
3
4
5
6
public ActionResult TempDataWay(int id)
{
   Book book = bookRepository.GetBook(id);
   TempData["Countries"] = new SelectList(PhoneValidator.Countries, book.Country);
   return View(book);
}

View取值的代码如下:

?
1
2
3
4
<div class="editor-field">
  <%= Html.DropDownList("Country", TempData["Countries"] as SelectList) %>
  <%: Html.ValidationMessageFor(model => model.Country) %>
</div>

效果:第一种方式一样。

TempData和ViewData的区别

做个简单的测试看下看下TempData和ViewData的区别

?
1
2
3
4
5
6
7
8
9
10
11
12
public ActionResult Test1()
{
  TempData["text"] = "1-2-3";
   ViewData["text"] = "1-2-3";
   return RedirectToAction("Test2");
}
public ActionResult Test2()
{
   string text1 = TempData["text"] as string;
  string text2 = ViewData["text"] as string;
   return View();
}

RedirectToAction跳转Action后,ViewData的值已经被清空,而TempData没有被清空,这是它们的区别之一。

希望本文所述对大家的asp.net程序设计有所帮助。

延伸 · 阅读

精彩推荐