开发工具与关键技术: VS MVC基础
作者:卢雅婷
撰写时间:2019/07/8
其实对于很多初学者来说ViewBag的使用方法都不算陌生,因为它的应用范围也是很广泛的。其实在我刚刚接触项目的开始就有关于ViewBag的使用,就我们的练习项目的登录的时候,用的就是ViewBag方法回填数据。
所以我在这里会以回填数据的例子来简单说明其的用法。因为我这个demo是通过页面的点击事件然后跳转页面回填数据的。所以我要获取其按钮的ID到控制器筛选我需要的那一条数据进行回填。
public ActionResult BookPlatform(int? TableListID)//房台预订
{
try
{首先是获取传过来的ID值传到页面。这里用的是ViewData方法,其实ViewBag也可以实现。
if(TableListID !=0 && TableListID != null)
{
ViewData[“TableListID”] = TableListID;
}//接着就是查询数据
var listCount = (from tbIndent in myModels.PW_Indent
join tbTableList in myModels.RM_TableList on tbIndent.TableListID equals tbTableList.TableListID
where tbTableList.TableListID == TableListID
select new suibian
{
TableNumber = tbTableList.TableNumber,//房台号
RoomTableName = tbTableList.RoomTableName,//房台名称
AccountNumber = tbIndent.AccountNumber, //账号
}).Single();
接着就是用ViewBag获取要回填的数据字段
ViewBag.TableNumber = listCount.TableNumber;
ViewBag.RoomTableName = listCount.RoomTableName;
ViewBag.AccountNumber = listCount.AccountNumber;
return View();
}
catch (Exception e)
{
Console.WriteLine(e);
return Json("failed", JsonRequestBehavior.AllowGet);
}
再到页面中使用ViewBag。如果要回填数据的是input标签,哪就直接在value中@ViewBag.(控制器传过来的数据)如下图
<div class="col-12 ml-2 pt-3">
<label class="col-form-label ml-3 layui-bg-blue pt-2 pb-2 pr-2 pl-3" style="border-radius:4px" for="searchFieldQuery" id="tabused">已用</label>
<input class="form-control-sm " style="margin-left:35px; width:40px;" value="@ViewBag.Count" id="used" disabled/>
<b>间</b>
</div
如果是在Js中使用则在声明全局变量中接收 如下
var TableListID =@ViewBag.TableListID;
或者可以直接使用@ViewBag.TableListID;如下图,即可
ViewBag的使用方法就说到这里了,如有更好的方法请留言,谢谢阅读。