ViewBag的使用方法

开发工具与关键技术: 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的使用方法就说到这里了,如有更好的方法请留言,谢谢阅读。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值