mvc:将视图模型代码转换为viewbag或viewdata

时间:2015-07-14 07:33:05

标签: model-view-controller viewmodel viewbag

我通过使用viewmodel将我的表数据发送到mvc网页....我的代码在下面..现在我被赋予了通过viewbag或viewdata发送它的任务。任何热情的程序员编辑代码发送它throgh viewbag或viedata并给出我们如何使用它们的基本概述,即viewmodel或viebag diffly。提前多了。

  @{
            ViewBag.Title = "Index";
        }

        <h2>Index</h2>
        <div>
        <br /><br />
          <table style="width: 100%;">

          <tr>
            <th>UserID</th>
            <th>UserName</th>       
            <th>Adress</th>
          </tr>

             @foreach(var item in ViewData.Model)
              {

           <tr>
            <td>@item.UserID</td>
            <td>@item.Username</td> 
            <td>@item.Adress</td>
          </tr>    
              }

            </table>
        </div>


    public class DetailController : Controller
        {
            public ActionResult Index()
            {
                ViewData.Model = DetailModels.GetData();
                return View();
            }

        }




    public class DetailModels
        {
            public static List<User> GetData()
            {
                EmployeeEntities context = new EmployeeEntities();
                List<User> dt = context.Users.AsEnumerable().ToList();
                return dt;
            }
        }

2 个答案:

答案 0 :(得分:0)

只需包含上面的库

@using ProjectName.Models

@foreach (Users u in Model)
{
       <td>@u.UserID</td>
        <td>@u.Username</td> 
        <td>@u.Adress</td>
}

答案 1 :(得分:0)

<强>控制器:

   public class DetailController : Controller
    {
        public ActionResult Index()
        {
          //  ViewData.Model = DetailModels.GetData();
              ViewData["DetailModels"] = DetailModels.GetData();
            return View();
        }
    }

查看:

    @foreach(var item in ViewData["DetailModels"] as DetailModels)
          {
           <tr>
             <td>@item.UserID</td>
             <td>@item.Username</td> 
             <td>@item.Adress</td>
           </tr>    
          }