开发者

how to display error message in Add/Edit dialogue of jqGrid while checking duplicate username?

开发者 https://www.devze.com 2023-04-03 06:53 出处:网络
I\'m checking duplicate username in Add/Edit Action of User Management and handle the code which is as under:

I'm checking duplicate username in Add/Edit Action of User Management and handle the code which is as under:

[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);
    }

The script code in .cshtml is as under:

 <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>

How can i display error message in Add/Edit Dialogue, please suggest.


the correct way will be to use some error HTML code in case of error. Instead of catching all exception in the server cage and returns return Json(false) you can throw exception which contains an error message. You can use [HandleJsonException] for example (see the answer) to encode any exceptions as simple JSON response with System.Net.HttpStatusCode.InternalServerError as HttpContext.Response.StatusCode. In the way you can post detailed error information to the jqGrid.

To decode the error information you can use errorTextFormat method in the same way as in decodeErrorMessage function from the same answer.

If you follow the way you will don't need to use any CheckUserName method. instead of that you can use method like .Save(user). The exception will be thrown automatically if needed. If you want to display more detailed error information you can catch for example SqlException, decode the information and produce another exception in the text of which you just includes information from the Server, Procedure, LineNumber, Message and so on properties of SqlException.

0

精彩评论

暂无评论...
验证码 换一张
取 消