tailieunhanh - Lập trình .net 4.0 và visual studio 2010 part 45

Vì vậy, điều này ViewData bạn chỉ được sử dụng là gì? Bạn có thể nghĩ ViewData như là một nơi để lưu trữ các đối tượng mà bạn sẽ sử dụng trong xem của bạn. Ví dụ, bạn có thể lưu trữ một lớp phim trong ViewData và sau đó liên kết với tính chất của nó. Cú pháp được sử dụng để truy cập vào các mục từ ViewData cũng tương tự như làm việc với ViewState. | CHAPTER 13 MVC Domain Controller Action ID http Product Detail 1 Figure 13-5. HowMVCseparates URLs Returning Views In the first example you returned a view that matched the action name Index . Views don t necessarily have to match the uRl although it is not a bad idea because it makes your intention clearer and reduces how much code you have to write. If you wanted to return the Index view you just created when the user navigates to an arbitrary address such as Film IWillAlsoReturnIndex you can do this with the following code public ActionResult IWillAlsoReturnIndex ViewData Message I am using Index view return View Index ViewData and TempData So what is this ViewData thing you just used You can think of ViewData as a place to store objects that you will use in your view. For example you might store a Film class in ViewData and then bind to its properties. The syntax used to access items from ViewData is similar to working with ViewState. Many developers don t like using ViewData because it is not strongly typed and involves some tedious casting operations when working with objects. My recommendation would be to avoid using it as much as possible. You will shortly look at a better way of binding data to a page. Related to ViewData is TempData. TempData is very similar except data added to it will be saved for only one post. TempData can be useful for storing and displaying items such as error messages that you don t want to maintain between posts. TempData is another controversial area that some developers dislike because they feel it is not in keeping with MVC s ideals. Displaying a List of Data You will now create a page to display a list of all the films. You need to add this functionality to the controller. 1. Open the file Controllers . 2. Add the following code at the top of the class to get an instance of the FilmRepository filmRepository public FilmController filmRepository new .