1
 public ActionResult GridSave(FormCollection data)
        {
            try
            {
                DataContext db = new DataContext();
                int Id = int.Parse(data["Id"]);

                var user = db.UserProfiles.Where(el => el.UserId == Id).FirstOrDefault();


                if (user == null)
                    return Content("Record not found.");

                if (data["FirstName"] != null)
                    user.FirstName = data["FirstName"];
                if (data["LastName"] != null)
                    user.LastName = data["LastName"];

                if (data["UserName"] != null)
                {
                    var strUsername = data["UserName"];
                    var tempUser = db.UserProfiles.SingleOrDefault(x => x.UserName.Trim() == strUsername.Trim() && x.UserId != Id);
                    if (tempUser != null)
                    {
                        return Content("\"" + strUsername + "\" already in use.");
                    }
                    else
                    {
                        user.UserName = strUsername;
                    }
                }
                if (data["Password"] != null)
                    user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(data["Password"], "sha1");
                if (data["PasswordExpiry"] != null)
                    user.Password_Expiry =Convert.ToString(data["PasswordExpiry"]);
                user.Modified = Convert.ToString(DateTime.Now);
                user.ModifiedBy = User.Identity.Name;
                //db.UserProfiles.Add(user);
                db.SaveChanges();

            }
            catch(Exception ex) 
            {
                return Content("System Error: "+ex);
            }
            return Json(true);
        }

i want to use this code in my project. but i don't know how to show error message using return Content() what should i do to show error message in jqgrid

this is my grid:

jQuery(document).ready(function () {
    var grid = jQuery("#grid");

    grid.jqGrid({
        url: '/Admin/GetContactsForJQGrid',
        datatype: 'json',
        mtype: 'Post',
        cellsubmit: 'remote',
        cellurl: '/Admin/GridSave',
        success:function(){alert(data)},
        formatCell: emptyText,
        colNames:['Id', '', 'First Name', 'Last Name', 'User Name', 'Password', 'Password Expiry', 'Last Modified', 'Last Modified By', 'Created By', ''],
            //['Id', 'Privileges', 'FirstName', 'LastName', 'UserName', 'Password', 'Type', 'Password_Expiry', 'CreatedBy', 'Modified', 'ModifiedBy'],
        colModel: [
            { name: 'Id', index: 'Id', width: "30", align: "left", key: true, hidden: true, editrules: { edithidden: true } },
            { name: 'Privileges', index: 'Privileges', width: 70, resizable: false, editable: false, align: 'center', formatter: formatLink, classes: 'not-editable-cell' },
            { name: 'FirstName', index: 'FirstName', align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
            { name: 'LastName', index: 'LastName', align: "left", sorttype: 'text', resizable: true, editable: true },
            { name: 'UserName', index: 'UserName', align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
            { name: 'Password', index: 'Password', align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
            { name: 'Type', width: "100", index: 'Type', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
            { name: 'Password_Expiry', index: 'Password_Expiry', align: "left", sorttype: 'date', resizable: true, editable: true, editrules: { required: true }, formatter: 'date', formatoptions: { srcformat: 'm/d/Y', newformat: 'm/d/Y' }, editoptions: { readonly: true, dataInit: function (el) { $(el).datepicker() } } },
            { name: 'CreatedBy', index: 'CreatedBy', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
            { name: 'Modified', index: 'Modified', sorttype: 'date', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
            { name: 'ModifiedBy', index: 'ModifiedBy', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' }



        ],
        shrinkToFit: true,
       //autowidth: true,
        pager: '#pager',
        height: '100%',
        width: "703",

        rowNum: 10,
         rowList: [10, 20, 50, 100],
        sortable: true,
        loadonce: false,
        ignoreCase: true,
        viewrecords: true,
        caption: 'Administration',
        cellEdit: true,
        hidegrid: false,
        viewrecords: true,
        gridComplete: function () {
            var ids = grid.jqGrid('getDataIDs');
            for (var i = 0; i < ids.length; i++) {
                var isDeleted = grid.jqGrid('getCell', ids[i], 'Delete');
                if (isDeleted == 'true') {
                    grid.jqGrid('setCell', ids[i], 'Delete', '<a href="#" onclick="deleteRow(' + ids[i] + ');"><img src="/Images/delete.png" alt="Delete Row" /></a>');
                }
                else {
                    grid.jqGrid('setCell', ids[i], 'Delete', ' ');
                    //grid.jqGrid('setCell', ids[i], 'Privileges', 'admin');
                }
            }
        }
    });

    grid.jqGrid('navGrid', '#pager',
        { resize: false, add: false, del: false, search: true, refresh: false, edit: false, alerttext: 'Please select one user' }

    ).jqGrid('navButtonAdd', '#pager',
        { title: "Add New users", buttonicon: "ui-icon ui-icon-plus", onClickButton: showNewUsersModal, position: "First", caption: "" });
});

what should i do in html to show the error message. i have added this line success:function(){alert(data)}, but alert does't show.

when i edit the record in grid...request goes to cellurl: '/Admin/GridSave', and from there (in controller,action result) i am returning the error message by using return Content("System Error: "+ex); but i don't know how exactly use content in mvc 4 vs 12

any suggestion will be appreciable :)

R K Sharma
  • 845
  • 8
  • 23
  • 42
  • to show the success message you have to use Public JsonResult GridSave(){} and then return Json(yourJsonData,jsonRequestBehaviour.AllowGet) – Mir Gulam Sarwar Nov 30 '13 at 17:26
  • ok, but i am asking about Content("System Error: "+ex); how should i use it – R K Sharma Nov 30 '13 at 18:19
  • that seems much complex to me, not sure but jqgrid has an afterSubmit function i think you sould look at it.Also look for @Oleg's answer.I didn't applied it yet but i have to. – Mir Gulam Sarwar Nov 30 '13 at 18:40

1 Answers1

0

It's not good to return just a text with Content("System Error: "+ex) from the method which return JSON too (see Json(true)). One can use return new EmptyResult(); for example instead of return Json(true);.

The code success:function(){alert(data)} will be ignored because jQuery supports callback success, but such callback is unknown for jqGrid. The list of callbacks supported by cell editing which you use you can find in the documentation. If you want return non-empty response in case of successful saving of data you can use afterSubmitCell or afterSaveCell callback.

For example afterSubmitCell can be used in the following way

afterSubmitCell: function (jqXHR) {
    alert(jqXHR.responseText);
    return [true]; // interpret the response as successful
}

jqGrid uses typically HTTP status code to detect whether the response of the server successful or not. The same do jQuery.ajax used by jqGrid internally. Some frameworks used on the server don't allow to set HTTP status code of the server response. In the case the callback afterSubmitCell is very helpful. One can analyse the server response and returns [true] in case of successful response and returns [false, "some error description"] in case of error. For example you can use some simple prefix like "!" in all error responses: return Content("!Record not found."); instead of return Content("Record not found.");, return Content("!\"" + strUsername + "\" already in use."); instead of return Content("\"" + strUsername + "\" already in use."); and so on. In the case you can use

afterSubmitCell: function (jqXHR) {
    if (typeof jqXHR.responseText === string && jqXHR.responseText.charAt(0) === "!") {
        return [false, jqXHR.responseText.substr(1)];
    } else {
        alert(jqXHR.responseText); // probably should be removed in the final version
        return [true]; // interpret the response as successful
    }
}

An alternative for usage of afterSubmitCell will be the usage of response having HTTP status code other as 200 (OK). For example you can use

public ActionResult GridSave (FormCollection data) {
    try {
        ...
        return new EmptyResult();
    } catch (Exception ex) {
        Response.StatusCode = 500;
        Response.TrySkipIisCustomErrors = true;
        return Content("System Error: " + ex.Message);
    }
}

or more better:

public ActionResult GridSave (FormCollection data) {
    try {
        ...
        return new EmptyResult();
    } catch (Exception ex) {
        Response.StatusCode = 500;
        Response.TrySkipIisCustomErrors = true;
        return new HttpStatusCodeResult(HttpStatusCode.InternalServerError,
                                        "System Error: " + ex.Message);
    }
}

In the case the callback afterSubmitCell will not be called in case of error. Instead of that you can use errorCell callback to display the error message. The corresponding code could be

errorCell: function (jqXHR) {
    $.jgrid.info_dialog($.jgrid.errors.errcap,
        jqXHR.status + " (" + jqXHR.statusText + "):<br/>" +
            jqXHR.responseText,
        $.jgrid.edit.bClose);
}

The above code uses $.jgrid.info_dialog instead of alert to display error message which more corresponds to jqGrid style. It's just an example of the usage. I wanted only to explain the possibilities which you have. The final code you should write yourself corresponds to exact reqirements of your project.

Be carefully with usage of the code which I included in my answer. I don't tested it, so some typing errors could exist.

Finally I would recommend you to use custom formatter instead of usage setCell in the loop inside of gridComplete. The current implementation is very slow in case of large number of rows. You should use gridview: true additionally to improve the performance.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798