MVC View 获取 控制器返回的ViewData和viewBag

js 获取

var vData=@Html.Raw(JsonConvert.SerializeObject(ViewData));

vData["step"]

html获取

@foreach (var item in ViewData["stepType"] as List<base_product_steptype>)
                        {
                            <option value=@item.id>@item.name</option>
                        }

 声明

public ActionResult Index()
        {
            ViewBag.UserName = "admin";
            ViewBag.Age = "25";
            string[] Itmes = new string[] { "中国", "陕西", "西安" };
            ViewBag.itemsA = Itmes;        
            return View();                 
        }

使用

<body>
    <div>
        username:<input type="text" id="UserName" name="UserName" value="@ViewBag.UserName" /></br>

        年  龄: <input type="text" id="age" name="age" value=@ViewBag.Age /></br>

        <button>提交</button>

        @foreach (dynamic item in ViewBag.itemsA)
        {
            <p>@item</p>
        }
    </div>
</body>
原文地址:https://www.cnblogs.com/ThisYbc/p/15040548.html