MVC 4 how pass data correctly from controller to view

前端 未结 4 1325
长发绾君心
长发绾君心 2020-11-29 08:30

I currently have a controller with a LINQ statement that i am passing data from to my view. I am trying to find a more efficient and better coding method to do this. My hom

4条回答
  •  臣服心动
    2020-11-29 09:24

    If you need to pass data actually from the controller and its data is depend on internal state or input controller parameters or has other properties of "business data" you should use Model part from MVC pattern:

    Model objects are the parts of the application that implement the logic for the application's data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.

    You can see details here or look to the Models and Validation in ASP.NET MVC part of Microsoft tutorial.

    1. Add model class:

      public class Person
      {
          public int Id { get; set; }
          public string Name { get; set; }
          public int Age { get; set; }
          public string City { get; set; }
      }
      
    2. Pass model object to the view:

      public ActionResult Index()
      {
          var model = GetModel();
          return View(model);
      }
      
    3. Add strongly typed View via define model type:

      @model Person
      
    4. Use Model variable in your view:

      @Model.City
      

提交回复
热议问题