0

I am implementing a simple CRUD operating. I have List of data displayed in table with capability of add edit and delete. Add edit and delete operation takes place in Jquery dialog

When i am trying to add a new record I return the Json result as Success True/false depending on the form data entry.

Here is my code

    [HttpPost]
    public ActionResult AddUser(AddCEQRUser addUserInfo)
    {            
        // perform insert operation

        if (ModelState.IsValid && InsertSuccess) 
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        else
            return Json(new { success = false }, JsonRequestBehavior.AllowGet);
    }

Partial view for add

@using (Html.BeginForm("AddUser", "Admin", FormMethod.Post, new { id = "addUserForm" }))
{
    @Html.AntiForgeryToken()
    <fieldset>
        <table class="headertable">

            // form elements
            <tr>
                <td align="center" colspan="2">
                    <button name="button" value="SubmitUser" class="button" id="btnSubmitUser">
                        Submit
                    </button>
                    &nbsp;
                    <button name="button" value="CancelAddUser" class="button" id="btnCancel">
                        Cancel
                    </button>
                </td>
            </tr>
        </table>
    </fieldset>
}

Ajax call on Submit button

$('#btnSubmitUser').click(function () {
        $.ajax({
            url: '@Url.Action("AddUser", "Admin", new { Area = "PrivateCEQRApplication" })',
            type: 'POST',
            dataType: 'json',
            cache: false,
            headers: headers,
            data: {
                FirstName: $('#txtFirstNameAdd').val(),
                MiddleName: $('#txtMiddleNameAdd').val(),
                LastName: $('#txtLastNameAdd').val(),
                EmailAddress: $('#txtEmailAddressAdd').val(),
                UserRole: $('#ddlUserRoleSelectedAdd').val()
            },
            beforeSend: function (xhr, settings) { xhr.setRequestHeader('__RequestVerificationToken', token); },
            success: function (data) {
                if (data.success) {
                    alert("The user has been added.");
                    $(".ui-dialog-content").dialog().dialog("close");
                }
                else {

                    //error handling

                }
            },
            error: function (xhr, textStatus, errorThrown) {
                alert("There was a problem with the operation. Please try again" + "Status: " + textStatus + "Error: " + errorThrown);
            }
        });
    });

Irrespective of whether there is an error or not when ever I click the Submit button I get a json file with { success : true } to download By IE. I have read quite a few article about this and how it says to set Content type application/json or text/html

If i set content type to application/json I still get prompted to download and if i set text/html a new page opens with { success : true }.

I also noticed if i put e.preventDefault(); in my btnSubmitUser click event I don't get prompted for download but then i loose the error handling.

All I want is for dialog to close if there is no error (json success true) by executing this code

alert("The user has been added.");
$(".ui-dialog-content").dialog().dialog("close");

and display error if any by executing the json success false block.

Your help will be greatly appreciated.

Thanks

DotNetBeginner
  • 412
  • 2
  • 15
  • 34
  • possible duplicate of [How can I convince IE to simply display application/json rather than offer to download it?](http://stackoverflow.com/questions/2483771/how-can-i-convince-ie-to-simply-display-application-json-rather-than-offer-to-do) – War10ck Jun 13 '14 at 15:45
  • 2
    You get that as the ajax request never finishes, the form is submitted instead. You *have* to have a preventDefault in the handler to avoid submitting the form when clicking the button. – adeneo Jun 13 '14 at 15:45
  • @adeneo can you please elaborate on what you mean by "ajax request never finishes" – DotNetBeginner Jun 13 '14 at 15:47
  • 1
    @DotNetBeginner, not that it never finishes, but since you are not preventing the default button behavior the form is posted, page is reloaded and there is no more code that can handle *this particular* response. So the default handling occur what response arrives. So in fact you should call `preventDefault` and trigger the validation manually – Andrei Jun 13 '14 at 15:52
  • @Andrei that makes sense. That for the explanation. Now i get a clear picture of what is going on. Appreciate your help. – DotNetBeginner Jun 13 '14 at 15:56

1 Answers1

0

As Adeneo says, you have to prevent the default action of the form submit to allow the javascript to complete. You can do this by adding event.preventDefault(); as the first line of your function (just below $('#btnSubmitUser').click(function () {) or by having the function return false.

Simon Brahan
  • 2,016
  • 1
  • 14
  • 22
  • I already know it will work with e.Preventdefault() if you read the post i have mentioned "I also noticed if i put e.preventDefault(); in my btnSubmitUser click event I don't get prompted for download but then i loose the error handling." Is there a way to get both. – DotNetBeginner Jun 13 '14 at 15:53
  • My mistake. I'm not sure why the error handling would go away just because of that. I'd check the response sent by your server script when you enter invalid information. Is it returning the success value as a string eg { "success": "false" }? That would be a truthy value and would prompt your success code to run. – Simon Brahan Jun 13 '14 at 16:06
  • I meant that the error handle by jquery.validate.min.js & jquery.validate.unobtrusive.min.js will not work. I will have to write a custom handling. – DotNetBeginner Jun 13 '14 at 16:41