如何将viewbag值与mvc 4中的另一个值进行比较

时间:2016-02-08 05:27:53

标签: asp.net-mvc entity-framework razor

我正在尝试从action方法发送viewbag来查看。当第一页加载viewbag值时将为null。当我调用CheckPermissions动作方法时,viewbag获取一些值,它将返回相同的视图,时间viewbag包含一些值,现在我想将viewbag值与另一个值进行比较。我试过但是出现了错误。无法对空引用执行运行时绑定。 这是我的索引视图代码。

@model c3card.Models.GroupPermissionVM
@{
    ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{
  @Html.LabelFor(m=>m.GroupID)
  @Html.DropDownListFor(m => m.GroupID, Model.GroupList, "Please select", new { id = "ddlgrp" })
    foreach(var permission in Model.Permissions)
    {
        if (ViewBag.marlid.equals(permission))
        {
        <label>
            @Html.RadioButtonFor(m => m.perm_id, permission.perm_id, new {@checked="true"})
            <span>@permission.perm_levelname</span>
        </label>
        }
        else
        {
            <label>
            @Html.RadioButtonFor(m => m.perm_id, permission.perm_id)
            <span>@permission.perm_levelname</span>
        </label>

        }
    }

这是我的行动方法

public ActionResult CheckPermissions(int id)
        {
            var groups = db.tm_grp_group.Where(a => a.grp_isactive == true);
            var permissions = db.tm_perm_level;
            GroupPermissionVM model = new GroupPermissionVM
            {
               marlid=db.ts_grp_perm_mapping.Select(p=>p.grp_id==id).Count(),
                GroupList = new SelectList(groups, "grp_id", "grp_name"),
                Permissions = permissions.Select(p => new PermissionVM
                {
                    perm_id = p.perm_id,
                    perm_levelname = p.perm_levelname

                })
            };
          ViewBag.marlid = db.ts_grp_perm_mapping.Select(p => p.grp_id == id).Count();

            return View("Index",model);
        }

任何建议为什么我无法比较条件内的值?提前致谢。这行导致我错误(ViewBag.marlid.equals(permission)) 我编辑如下

foreach(var permission in Model.Permissions)
    {
       if(Model.marlid==permission.perm_id)
       {
          <label>
            @Html.RadioButtonFor(m => m.perm_id, permission.perm_id,new { @checked = true } )@Model.marlid.ToString()
            <span>@permission.perm_levelname</span>
        </label>

       }

1 个答案:

答案 0 :(得分:4)

您可以更改下面给出的代码

if(ViewBag.marlid != null && Model.Permissions != null)
    {
        foreach(var permission in Model.Permissions)
        {
           if(ViewBag.marlid == permission.perm_id)
           {
              <label>
                @Html.RadioButtonFor(m => m.perm_id, permission.perm_id,new { @checked = true } )@Model.marlid.ToString()
                <span>@permission.perm_levelname</span>
            </label>
           }
        }
    }

希望这有帮助。