如何在检查重复的用户名时在jqGrid的“添加/编辑”对话框中显示错误消息?

时间:2011-09-08 10:39:20

标签: jqgrid

我正在用户管理的添加/编辑操作中检查重复的用户名,并处理以下代码:

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult InsertUser(UserViewModel viewModel)
    {
        var user = new User
                       {
                           UserID = viewModel.UserID,
                           UserName = viewModel.UserName,
                           //Password = "123456",
                           Password = viewModel.Password,
                           FullName = viewModel.FullName,
                           Email = viewModel.Email,
                           CreationDate = DateTime.Now,
                           IsActive = viewModel.IsActive
                       };

        //Also check here if user already exist, usename shud be unique.
        bool isAlreadyExist = new UserManagement().CheckUserName(user.UserName);

        if(isAlreadyExist)
        {
            return Json(false);
        }

        try
        {
            new UserManagement().Save(user);
        }
        catch (Exception)
        {
            return Json(false);
        }

        return Json(true);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult UpdateUser(UserViewModel viewModel)
    {
        User user = new UserManagement().GetUserBy(viewModel.UserID);


        if (!viewModel.UserName.TrimEnd().Equals(user.UserName.TrimEnd()))
        {
            bool isAlreadyExist = new UserManagement().CheckUserName(viewModel.UserName);

            if (isAlreadyExist)
            {
                return Json(false);
            }

        }

        user.UserName = viewModel.UserName;
        user.Password = viewModel.Password;
        user.FullName = viewModel.FullName;
        user.Email = viewModel.Email;
        user.IsActive = viewModel.IsActive;

        try
        {
            new UserManagement().Save(user);
        }
        catch
        {
            return Json(false);
        }

        return Json(true);
    }

.cshtml中的脚本代码如下:

 <script type="text/javascript">
    var arrayIds = [];
    var roleDropDown = "";

    $(document).ready(function () {
        $(".ui-dropdownchecklist > div > div > .active").live("change", function () {
            var parentId = $(this).parent().parent().parent().attr("Id");
            parentId = parentId.substring(0, parentId.length - 4);
            $("#" + parentId + " > span > span").text("Assigning...").css("color", "#666666");

            //Set Variable to identify Assign or Deassign Role to User
            var checked = false;
            if ($(this).attr("checked") == "checked") {
                checked = true;
            }
            //Set RoleId
            var role = $(this).val();
            //Set UserId
            var user = $(this).attr('id');

            //Start Ajax Call
            $.ajax({
                url: '@Url.Action("ManageUserRoles", "Role")',
                type: "GET",
                cache: false,
                data: { userid: user, roleid: role, chked: checked },
                //async: false,
                success: function () {
                },
                complete: function () {
                    $("#" + parentId + " > span > span").text("Assign Roles").css("color", "#222222");
                }
            });
            //End Ajax Call
        });

        roleDropDown = "<select id='_RoleID' multiple='true' style='Display: none;'>";
        $.ajax({
            url: '@Url.Action("GetAllReoles", "Role")',
            type: "GET",
            cache: true,
            async: false,
            success: function (countiesJson) {
                $.each(countiesJson, function (index, optionData) {
                    roleDropDown += "<option value='" + optionData.RoleID + "'>" + optionData.RoleName + "</option>";
                });
            }
        });
        roleDropDown += "</select>";

        var userGrid = $('#jqgUsers');
        var pages = [];
        var MAX_PAGERS = 2;

        $('#jqgUsers').jqGrid({
            //url from wich data should be requested
            url: '@Url.Action("FetchUsers")',
            //type of data
            datatype: 'json',
            cache: false,
            //url access method type
            mtype: 'POST',
            postData: {
                UserName: function () { return $('#UserName1').val(); },
                FullName: function () { return $('#FullName1').val(); },
                Email: function () { return $('#Email1').val(); },
                IsActive: function () { return $('#IsActive1 option:selected').val(); },
                FromDate: function () { return $('#FromDate').val(); },
                ToDate: function () { return $('#ToDate').val(); }
            },
            colNames: ['User ID', 'User Name', 'Password', 'Full Name', 'Email', 'Active', 'Roles', ''],
            //columns model
            colModel: [
                        { name: 'UserID', index: 'UserID', hidden: true, align: 'left', editable: false },
                        { name: 'UserName', index: 'UserName', width: 252, align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 50 }, editrules: { required: true} },
                        { name: 'Password', index: 'Password', hidden: true, width: 175, align: 'left', editable: true, edittype: 'password', editoptions: { maxlength: 20 }, editrules: { required: true, edithidden: true} },
                        { name: 'FullName', index: 'FullName', width: 245, align: 'left', editable: true, edittype: 'text', editoptions: { maxlength: 100 }, editrules: { required: true} },
                        { name: 'Email', index: 'Email', width: 247, align: 'left', formatter: emailFormatter, sortable: true, editable: true, edittype: 'custom', editoptions: { custom_element: mymailelem, custom_value: mymailvalue }, editrules: { required: true, email: true} },
                        { name: 'IsActive', index: 'IsActive', width: 85, formatter: imgformatter, sortable: true, align: 'center',
                            editable: true, edittype: 'custom', editoptions: { custom_element: myelem, custom_value: myvalue }
                        },
                        { name: 'role', index: 'role', width: 120, formatter: RoleCobFormatter, sortable: true, align: 'left' },
                        { name: 'act', index: 'act', width: 55, align: 'center', sortable: false, formatter: 'actions',
                            formatoptions: {
                                keys: true,
                                editformbutton: true,
                                delbutton: true,
                                editOptions: {
                                    url: '@Url.Action("UpdateUser")',
                                    closeAfterEdit: true
                                },
                                delOptions: {
                                    url: '@Url.Action("DeleteUser")'
                                }
                            }
                        }
                      ],
            pager: $('#jqgpUsers'),
            rowNum: 10,
            pginput: false,
            rowList: [10, 20, 50, 100],
            sortname: 'UserID',
            sortorder: 'asc',
            viewrecords: true,
            height: 'auto',
            loadComplete: function () {

                if (pages[$('#jqgUsers').getGridParam('page')] != null) {
                    var selRows = pages[$('#jqgUsers').getGridParam('page')];
                    var i;
                    var limit = selRows.length;
                    for (i = 0; i < limit; i++) {
                        $('#jqgUsers').setSelection(selRows[i], true);
                    }
                }
                //-------Start Paging Style
                var i, myPageRefresh = function (e) {
                    var newPage = $(e.target).text();
                    userGrid.trigger("reloadGrid", [{ page: newPage}]);
                    e.preventDefault();
                };

                //variables
                var currentPage = this.p.page;
                var startPage;

                var totalPages = this.p.lastpage;
                if (this.p.records == 0) {
                    totalPages = 0;
                }

                if (this.p.page - MAX_PAGERS <= 0) {
                    startPage = 1;
                }
                else {
                    startPage = this.p.page - MAX_PAGERS;
                }
                var lastPage;
                if (this.p.page + MAX_PAGERS >= totalPages) {
                    lastPage = totalPages;
                }
                else {
                    lastPage = this.p.page + MAX_PAGERS;
                }

                $(userGrid[0].p.pager + '_center td.myPager').remove();
                //---- Variables End
                if (totalPages > 1) {

                    var pagerPrevTD = $('<td>', { "class": "myPager" }), prevPagesIncluded = 0,
                    pagerNextTD = $('<td>', { "class": "myPager" }), nextPagesIncluded = 0,
                    totalStyle = userGrid[0].p.pginput === false,
                    startIndex = totalStyle ? this.p.page - MAX_PAGERS * 2 : this.p.page - MAX_PAGERS;

                    for (i = startPage; i <= lastPage; i++) {
                        if (i <= 0) { continue; }
                        var link = $('<a>', { href: '#', click: myPageRefresh, "class": "Paging" });
                        if (i == this.p.page) { link.attr("class", "selected"); }

                        link.text(String(i));

                        if (i < this.p.page || totalStyle) {
                            pagerPrevTD.append(link);
                            prevPagesIncluded++;
                        } else {
                            if (nextPagesIncluded > 0 || (totalStyle && prevPagesIncluded > 0)) { pagerNextTD.append('<span>,&nbsp;</span>'); }
                            pagerNextTD.append(link);
                            nextPagesIncluded++;
                        }
                    }
                    if (prevPagesIncluded > 0) {
                        $(userGrid[0].p.pager + '_center td[id^="prev"]').after(pagerPrevTD);
                    }
                    if (nextPagesIncluded > 0) {
                        $(userGrid[0].p.pager + '_center td[id^="next"]').before(pagerNextTD);
                    }
                }
                else {
                    //$('#first_jqgpFlagger').unbind();
                    $('#first_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
                    //$('#prev_jqgpFlagger').unbind();
                    $('#prev_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
                    //$('#next_jqgpFlagger').unbind();
                    $('#next_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
                    //$('#last_jqgpFlagger').unbind();
                    $('#last_jqgpUsers').attr('class', 'ui-corner-all ui-state-disabled');
                }
                //-------End Paging Style
            },
            gridComplete: function () {
                $.each(arrayIds, function (index, optionData) {
                    $.ajax({
                        url: '@Url.Action("GetRolesbyUserId", "Role")' + '/' + optionData.substring(4),
                        type: "GET",
                        cache: false,
                        async: false,
                        success: function (countiesJson) {
                            $.each(countiesJson, function (index, optionItem) {
                                $("#" + optionData + " option[value='" + optionItem.RoleID.toString() + "']").attr("selected", "selected");
                            });
                        }
                    });
                    if ($("#ddcl-" + optionData).length > 0) {
                        $("#ddcl-" + optionData).remove();
                        $("#ddcl-" + optionData + "-ddw").remove();
                    }
                    $("#" + optionData).dropdownchecklist({ emptyText: "Assign Roles" });
                }); //End Each Loop
            }
        });
        $('#jqgUsers').jqGrid('navGrid', '#jqgpUsers',
            { add: true, del: false, edit: false, search: false },
            { width: '250', closeAfterEdit: true, url: '@Url.Action("UpdateUser")' },
            { width: '250', closeAfterAdd: true, url: '@Url.Action("InsertUser")' },
            { width: '250', url: '@Url.Action("DeleteUser")' });

        $('#CustomPanel').appendTo('.ui-jqgrid-hbox');
        $(".ui-jqgrid-sortable").attr("style", "height: 32px");

        $('#UserName1').blur(function () {
            $('#jqgUsers').trigger("reloadGrid");
        });

        $('#FullName1').blur(function () {
            $('#jqgUsers').trigger("reloadGrid");
        });

        $('#Email1').blur(function () {
            $('#jqgUsers').trigger("reloadGrid");
        });

        $('#IsActive1').change(function () {
            $('#jqgUsers').trigger("reloadGrid");

        });

        $('#btnClear').click(function () {
            $('#UserName1').val('');
            $('#FullName1').val('');
            $('#Email1').val('');
            $('#IsActive1 option:eq(0)').attr('selected', 'selected');
            $('#jqgUsers').trigger("reloadGrid");
        });

    });

    function emailFormatter(cellvalue) {
        email = "<a href='mailto:" + cellvalue + "'>" + cellvalue + "</a>";
        return email;
    }

    function mymailelem(value, options) {
        var e1 = document.createElement("input");
        e1.type = "text";
        if (value != "") {
            value = value.split('>')[1].split('<')[0];
        }
        e1.value = value;
        z = document.createAttribute('class');
        z.value = 'FormElement ui-widget-content ui-corner-all';
        e1.setAttributeNode(z);
        return e1;
    }

    function mymailvalue(elem, operation, value) {
        if (value != undefined) {
            value = value.split('>')[1].split('<')[0];
        }
        else {
            value = '';
        }
        if (operation === 'get') {
            return $(elem)[0].value;
        } else if (operation === 'set') {
            $(elem).val(value);
        }
    }

    function imgformatter(cellvalue, options, rowObject) {
        if (cellvalue == 'True') {
            ActiveImage = "<img border='0' src='../../Content/images/tick.png' alt='' width='16px' height='16px' style='padding-top: 7px;'  />";
        }
        else {
            ActiveImage = "<img border='0' src='../../Content/images/cross.png' alt='' width='16px' height='16px' style='padding-top: 7px;'  />";
        }
        return ActiveImage;
    }

    function RoleCobFormatter(cellvalue, options, rowObject) {
        var id = "sel-" + options.rowId.toString();
        arrayIds.push(id);
        var retVal = roleDropDown.replace('_RoleID', id);
        return retVal;
    }

    function myelem(value, options) {
        var el = document.createElement("input");
        el.type = "checkbox";
        if (value.indexOf('tick') != -1) {
            value = 'checked';
            el.checked = 'checked';
        }
        else {
            value = '';
            el.checked = '';
        }
        return el;
    }

    function myvalue(elem, operation, value) {
        if (value != undefined && value.indexOf('tick') != -1) {
            value = 'checked';
        }
        else {
            value = '';
        }
        if (operation === 'get') {
            //                return $(elem).find("input").val();
            return $(elem).is(':checked');
        } else if (operation === 'set') {
            //                $('input', elem).val(value);
            //            $('input', elem).attr('checked', value);
            $(elem)[0].checked = value;
        }
    }

</script>

如何在添加/编辑对话中显示错误消息,请建议。

1 个答案:

答案 0 :(得分:2)

正确的方法是在出现错误时使用一些错误的HTML代码。而不是捕获服务器笼中的所有异常并返回return Json(false),您可以抛出异常,其中包含错误消息。您可以使用[HandleJsonException](例如the answer)将任何例外编码为System.Net.HttpStatusCode.InternalServerError作为HttpContext.Response.StatusCode的简单JSON响应。您可以将详细的错误信息发布到jqGrid。

要解码错误信息,您可以使用errorTextFormat方法,方法与the same answer中的decodeErrorMessage函数相同。

如果按照您的方式操作,则无需使用任何CheckUserName方法。而不是你可以使用像.Save(user)这样的方法。如果需要,将自动抛出异常。如果您想显示更详细的错误信息,例如SqlException,请解析信息并在文本中生成另一个例外,其中只包含来自ServerProcedure的信息, LineNumberMessage等属性SqlException