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