[ASP.NET_MVC]利用viewbag變數傳遞model資料

  • 1579
  • 0

[ASP.NET_MVC]利用viewbag變數傳遞model資料

在controller裡面先抓好資料:

public ActionResult ViewBagToModel()
{
	ViewBag.routes = db.CyclingRoutes.ToList();
	return View(ViewBag.routes);
}



然後View裡面直接引用,但記得做轉型成強型別比較方便使用:
var routes = ViewBag.Routes as List;

@{
    ViewBag.Title = "ViewBagToModel";
}

<h2>ViewBagToModel</h2>

<div class="container-fluid">

    <h1>Try to pass ViewBas as a model</h1>
    
    @{
        var routes = ViewBag.Routes as List<CyclingRoutesMeetup.Models.CyclingRoutes>;
    }

    @if (routes.Count() > 0)
    {


        foreach (var item in routes)
        {

            <div class="row">
                <div class="col-sm-4 col-md-3 col-lg-2">@Html.DisplayFor(modelItem => item.RouteName) </div>
                <div class="col-sm-4 col-md-3 col-lg-2">@Html.DisplayFor(modelItem => item.Distance)</div>
                <div class="col-sm-4 col-md-6 col-lg-8">@Html.DisplayFor(modelItem => item.RidingTime)</div>

            </div>
        }
    }

</div>

此範例有套用版型,_layout.cshtml的內容可以直接參考這篇複製貼上:
[MVC5_004]新增View檢視來顯示(查詢部分)的資料

執行結果:


這篇大概是這樣。。。