如果记录存在,则在mvc的viewbag中显示错误消息

时间:2016-05-06 05:53:58

标签: asp.net-mvc asp.net-mvc-4

这里我有一个场景,我想检查记录是否已经存在,然后在视图上显示错误消息。如果记录不存在则渲染局部视图,如果记录不存在则意味着添加记录成功渲染局部视图。 在viewbag.i试过但失败了,任何人都可以帮忙。 先感谢您 控制器操作方法

public ActionResult ManageRole(TBL_ADMIN_ROLE role)
        {
            if (dbcontext.TBL_ADMIN_ROLE.Any(role1 => role1.RoleName.Equals(role.RoleName) && role1.IsDeleted == 0))
            {

                ViewBag.ExistsRecord = "Record Already Exists";
            }
            if (TryUpdateModel(role))
            {
                if (ModelState.IsValid)
                {
                    role.IsDeleted = 0;
                    role.CreatedDateTime = DateTime.Now;
                    dbcontext.TBL_ADMIN_ROLE.Add(role);
                    role.CreatedByID = Convert.ToInt32(Session["UserID"]);
                    dbcontext.SaveChanges();
                    dbcontext.Configuration.ProxyCreationEnabled = false;
                    List<TBL_ADMIN_ROLE> roleList = dbcontext.TBL_ADMIN_ROLE.Where(x => x.IsDeleted == 0).ToList();
                    return PartialView("_ManageRoleList", roleList);
                }
            }
            return View(role);

        }

查看

    @using (Ajax.BeginForm("ManageRole", "Security", null, new AjaxOptions
    {
        HttpMethod = "POST",
        UpdateTargetId = "DisplayRoleGrid",
        InsertionMode = InsertionMode.Replace,
        OnSuccess = "oNsuccess"
    }))
    {

        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <div id="divmessage">
            <label id="successmessage"></label>
        </div>
        <div class="row">
            <div class="col-lg-3"></div>
            <div class="col-lg-4">
               @ViewBag.ExistsRecord
            </div>
        </div>
 <div class="col-lg-4">


            @(Html.Kendo().TextBox().Name("RoleName")
                  .HtmlAttributes(new { @class = "form-control", placeholder = "Role Name", required = "required", validationmessage = "Enter {0}", data_required_msg = "Enter Role Name" }))

        </div>
    }

1 个答案:

答案 0 :(得分:0)

if (dbcontext.TBL_ADMIN_ROLE.Any(role1 => role1.RoleName.Equals(role.RoleName) && role1.IsDeleted == 0)) { ViewBag.ExistsRecord = "Record Already Exists"; Return View(Role); }

不确定你要做什么。您不必使用Viewbag执行此操作以返回错误。您可以对此

使用AddModelError