Three ways to pass values to the view of the ASP.

Source: Internet
Author: User

Transferred from: http://www.cnblogs.com/shinima/p/3940452.html

1. Providing a view model object

You can pass an object to the view as a parameter of the view method.

    1. Public ViewResult Index ()
    2. {
    3. DateTime date = DateTime.Now;
    4. return View (date);
    5. }

We then use the Razor model keyword in the view to access the object

    1. @{
    2. Viewbag.title = "Index";
    3. }
    4. The day is : @ ((DateTime) Model). DayOfWeek)

or a

    1. @model DateTime
    2. @{
    3. Viewbag.title = "Index";
    4. }
    5. The day is : @Model. DayOfWeek

2. Passing Data using ViewBag (view pack)

View Bag allows you to define any property on a dynamic object and access it in a view. This dynamic object can be accessed through the Controller.viewbag property.

  1. Public ViewResult Index ()
  2. {
  3. Viewbag.message = "Hello";
  4. Viewbag.date = DateTime.Now;
  5. return View ();
  6. }
  7. @{
  8. Viewbag.title = "Index";
  9. }
  10. The day is : @ViewBag. Date.dayofweek
  11. <p/>
  12. The message is : @ViewBag. Message

3. Passing Data using view data

Before MVC3.0, the main way to pass data is by using the Viewdatadictionary class instead of a dynamic object. The Viewdatadictionary class is similar to the standard "key/value" collection and is

The ViewData property of the controller class is accessed. This method requires that the object be converted in the view.

  1. In the controller:
  2. Public ViewResult Index ()
  3. {
  4. viewdata["Message"] = "Hello";
  5. viewdata["Date"] = DateTime.Now;
  6. return View ();
  7. }
  8. In the View:
  9. @{
  10. Viewbag.title = "Index";
  11. }
  12. The day is : @ (((DateTime) viewdata["Date"). DayOfWeek)
  13. <p/>
  14. The message is : @ViewData ["message"]

Three ways to pass values to the view of the ASP.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.