Why querystring after ajax call while using datatable checkboxes? - c#

I am trying to save the data by selecting multi checkboxes in datatables. But after ajax call in the submit click the the ajax not hitting success function. It is showing querystring along with the controller/action.Like following
https://localhost:44307/Leaves/Approval?leaveApproveDataTable_length=10&id%5B%5D=11
This is my js
$(document).on('click', '.btn-Approve', function (e) {
var form = this;
var rows = $(table.rows({
selected: true
}).$('input[type="checkbox"]').map(function () {
return $(this).prop("checked") ? $(this).closest('tr').attr('leaveid') : null;
}));
rows_selected = [];
$.each(rows, function (index, rowId) {
console.log(rowId)
// Create a hidden element
rows_selected.push(rowId);
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
var remarks = $('#Remarks').val();
console.log($(this).closest('tr').attr('leaveid'));
$.ajax({
url: '/Leaves/LeaveApproval',
data: { approveId: rows_selected, remarks: remarks },
type: 'POST',
processData: true,
dataType: 'JSON',
success: function (result) {
console.log(result);
debugger;
if (result) {
window.location.href = "/Leaves/Approval";
}
else {
return result;
}
},
error: function () {
}
});
});
This is my controller
public async Task<IActionResult> LeaveApproval(List<int> approveId, string remarks)
{
foreach (int id in approveId)
{
var leave = await _context.Leaves.FindAsync(id);
if (leave == null)
{
return Json(new { success = false });
}
leave.Status = "Approved";
leave.Remarks = remarks;
leave.ApprovedDate = DateTime.Now;
_context.Update(leave);
await _context.SaveChangesAsync();
}
return Json(new { success = true });
}
Kindly help me to solve the issue.

While returning from the controller replace:
return Json(new { success = true }); this line with
return Json(new { success = true }, JsonRequestBehavior.AllowGet);

Related

MVC Redirecting Action using Json

Purpose: The code written is suppose to save all the contents using Json and re direct to action.
Problem:
The current redirect using Json does not allow the redirection as suppose.
return new JsonResult { Data = new { status = status } };
The code is below for reference: Looking for suggestions:
View Code
$.ajax({
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
//check is successfully save to database
if (d.status == true) {
//will send status from server side
alert('Successfully done.');
window.location.href = d.Url;
//clear form
t = [];
d = [];
r = [];
$('#SN').val('');
$('#SA').val('');
$('#t').empty();
$('#d').empty();
$('#r').empty();
}
else {
alert('Failed');
}
$('#submit').val('Save');
},
});
Controller
public JsonResult Save(SAVM O,)
{
bool status = false;
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
SA s = new SA
{
}
_db.SA.Add(O)
_db.SaveChanges();
status = true;
}
else
{
status = false
}
return new JsonResult { Data = new { status = status } };
}
Here want to redirect like this:
return RedirectToAction("F", "SA");
but using JsonResult
Solution
View
$.ajax({
url: '/SA/Save',
type: "POST",
data: JSON.stringify(data),
dataType: "JSON",
contentType: "application/json",
success: function (d) {
window.location.href = d.Url;
})
} });
Controller
public JsonResult Save(SAVM O,)
{
var userId = User.Identity.GetUserId();
if (ModelState.IsValid)
{
SA s = new SA
{
}
_db.SA.Add(O)
_db.SaveChanges();
return Json(new { Url = "F/SA" });
}
You have a couple of options here, you decide which one you prefer based on your requirements.
Do not use AJAX. AJAX requests are meant for data required for the current page. You should use a synchronous request for the redirection.
Return the URL to which the client should redirect on the success event:
return Json(new { url = "/F/SA" });
And then:
success: function (d)
{
window.location.url = d.url;
}
Return the already rendered View and load it to the current page:
return View("some view...");
And then:
success: function (d)
{
$("#someElement").html(d);
}

Sending object to a controller in asp.net mvc using ajax

I have issue with sending object contains array to a controller
this is my js code
var messageId = 0;
function DraftMessage()
{
var to = [];
var i = 0;
$('#to option:selected').each(function (index, element) {
to[i++] = $(element).val();
});
console.log(to);
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage", "Activities")",
datatype: "json",
traditional: true,
async: false,
data: { "id": messageId, "To": to, "Title": $("#title").val(), "Project": $("#project").val(), "AreaId": $("#areaId").val(), "Body": $("#messageBody").val() },
beforeSend: function () { }
}).done(function (Id) {
console.log(Id);
messageId = Id;
});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
and this is my controller side
public int DraftMessage(message draftMessage, HttpPostedFileBase[] files = null)
{
return new MessageActions().DraftMessage(draftMessage);
}
my issue is that the ajax request always send the to array as null, I do not know what is wrong so could anyone help me to resolve this issue.
Can you change your request and use
dataType: "json",
contentType: "application/json;charset=utf-8",
This should work. Please let me know.
Try this. Push your object to array and send it as Json.
array.push({yourobject datas here})
$.ajax({
type: "POST",
url: '/DraftMessage/Activities',
contentType: 'application/json',
data: JSON.stringify(array),
success: function (d) {
..
},
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
Convert your controller function's return type to JSonResult.
Hope helps.
do you want upload file using ajax ?!!
use the normal usage of form not the Ajax.BeginForm then in form submit event
write your code like this:
$('#Form').submit(function () {
var xhr = new XMLHttpRequest();
var fd = new FormData();
var file = $('#Image').val();
if (file) {
var fname = $('#Image')[0].files[0].name;
if (CheckFile(file)) {
var uploadFile = document.getElementById('Image').files[0];
var myArray = [];
myArray.push(uploadFile);
if (myArray.length > 0) {
for (var i = 0; i < myArray.length; i = i + 1) {
fd.append("File1", myArray[i]);
}
}
}
else {
return false;
}
}
fd.append("ID", messageId);
fd.append("Title", $('#Title').val());
fd.append("Project", $('#Project').val());
fd.append("AreaId", $('#AreaId').val());
fd.append("Body", $('#messageBody').val());
var form = $('#Form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
fd.append("__RequestVerificationToken", token);
xhr.open("POST", "/ControllerName/Action/", true);
xhr.send(fd);
xhr.addEventListener("load", function (event) {
if (event.target.response != "OK") {
OnFail(event.target.response);
}
else {
OnSuccess(event);
}
}, false);
return false;
})
server side in controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult actionName(Model pModel){
HttpPostedFileBase File = Request.Files["File1"];
if (File != null && File.ContentLength != 0){
//do what you want
return Content("OK");
}
else{
Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return Content("Error Messages", System.Net.Mime.MediaTypeNames.Text.Plain);
}
}
You can try a different approach. You can serialize your entire form by doing something like this:
var formdata = $("#frmEmailInfo").serialize();
and then post it to the Controller:
$.ajax(
{
type: "POST",
data: formdata,
dataType: 'json',...

Display a confirmation message on Delete a record from a Grid

I want to display a confirmation message when the User delete a record from a grid this what I implement but I have the error message
With the code below the record is deleted but :
the record still in the Grid I have to refresh to see it disapear;
I Have the message Error! even if the record is deleted
3.
#Html.ActionLink("Delete Student", "Delete", new { #StudentID = StudentID }, new { #class="glyphicon glyphicon-pencil", #id=StudentID })
$(document).ready(function () {
$('a.delete').click(OnDeleteClick);
});
function OnDeleteClick(e)
{
var StudentId = e.target.id;
var flag = confirm('You are about to delete this record permanently. Are you sure you want to delete this record?');
if (flag) {
$.ajax({
url: '/Home/DeleteRecord',
type: 'POST',
data: { StudentID: StudentId },
dataType: 'json',
success: function (result) {
alert(result);
$("#" + StudentId).parent().parent().remove();
},
error: function () {
alert('Error!');
}
});
}
return false;
}
Controller :
public ActionResult DeleteRecord(string StudentID)
{
//Code to delete
}
return RedirectToAction("StudentGrid",
"Home");
}
Without seeing which grid you are using try the following:
Get the closest tr tag so you can remove it on success with:
var $tr = $(this).closest("tr");
$tr.remove();
jsFiddle
Set the content message from your controller, the Redirect won't work as it is an ajax call.
public ActionResult DeleteRecord(string StudentID)
{
var success = false;
//Code to delete
// then set success variable
if (success)
{
return Content("Deleted");
}
else
{
return Content("Failed");
}
}
Then from your success handler check the message and remove if needed, the client-side code would end up like this:
function OnDeleteClick(e)
{
e.preventDefault();
var $tr = $(this).closest("tr");
var StudentId = e.target.id;
var flag = confirm('You are about to delete this record permanently. Are you sure you want to delete this record?');
if (flag) {
$.ajax({
url: '/Home/DeleteRecord',
type: 'POST',
data: { StudentID: StudentId },
dataType: 'json',
success: function (result) {
if (result == "Deleted")
$tr.remove();
},
error: function () {
alert('Error!');
}
});
}
return false;
}
public ActionResult DeleteRecord(string StudentID)
{
//Code to delete
}
return Json("Record Is Delete", JsonRequestBehavior.AllowGet);
}
with is response from controller you can show this MSG in alert()
with update grid in project you can use below code is sufficient
$(e).closest("tr").remove();

Jquery overriding global value

I am using kendo ui and i dont want duplicate records in my database so what i am doing is using the .Save function of kendo grid to check the record and if exist then return false which is working fine but when i am returning return false then it is still saving the record.
function onSave(e) {
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax(
{
url: '/StudentTransaction/CheckRegistrationNumber',
type: "POST",
data: { 'RegisterNumber': currentValueForSend },
success: function (data) {
alert(data.CurrentRegNo);
if( data.CurrentRegNo.indexOf('true') >= 0){
alert("no duplicate records");
return false;;
}
}
});
}
i am also defining a global value to override the value but i am not able to override the value
function onSave(e) {
var status;
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax(
{
url: '/StudentTransaction/CheckRegistrationNumber',
type: "POST",
data: { 'RegisterNumber': currentValueForSend },
success: function (data) {
status = data.CurrentRegNo;
}
});
if (status.indexOf('true') >= 0)) {
e.preventDefault();
alert("Duplicates not allowed");
return false;
}
}
What i am doing wrong?
This is due to the async nature of these requests.
The sequence as described in your code is:
make the request
check if status is true
get the response
You need to use function callbacks to handle this properly. Try something like this:
function onSave (e){
var currentValueForSend = $("[name=RegisterNo]").val();
alert(currentValueForSend);
$.ajax({
url : '/StudentTransaction/CheckRegistrationNumber',
type : "POST",
data : { 'RegisterNumber': currentValueForSend },
success : afterSave
});
}
function afterSave (data){
var status = data.CurrentRegNo;
if (status.indexOf('true') >= 0)) {
e.preventDefault();
alert("Duplicates not allowed");
return false;
}
}

Resume form submission after $.ajax call

How can I resume/stop form submission after jQuery ajax call?
I have MVC application, I'm calling an action by json, I want to stop form submission if result came false and to resume if result came true.
Jquery:
$("#formElem").submit(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("Check", "TimeRanges")',
type: "GET",
data: {startRange: $('#SelectedStartTimeRange').val() , endRange: $('#SelectedEndTimeRange').val()},
aync: false,
dataType: 'json',
success: function (data) {
if(data == false) {
$("#rangeexist").html('Error');
return false;
} else {
return true;
}
}
});
});
Action
public JsonResult Check(string startRange, string endRange)
{
var result = false;
if (!String.IsNullOrEmpty(startRange) && !String.IsNullOrEmpty(endRange))
{
TimeSpan spanStart;
TimeSpan.TryParse(startRange, out spanStart);
TimeSpan spanEnd;
TimeSpan.TryParse(endRange, out spanEnd);
var timeRangExisted = _repo.All().Where(x => x.TimeFrom.Equals(spanStart) && x.TimeTo.Equals(spanEnd)).ToList();
if (!timeRangExisted.Any())
result = true;
}
return Json(result, JsonRequestBehavior.AllowGet);
}
var ajaxSent = false;
$("#formElem").submit(function (e) {
if ( !ajaxSent )
e.preventDefault();
$.ajax({
url: '#Url.Action("Check", "TimeRanges")',
type: "GET",
data: {startRange: $('#SelectedStartTimeRange').val() , endRange: $('#SelectedEndTimeRange').val()},
aync: false,
dataType: 'json',
success: function (data) {
if(data == false) {
$("#rangeexist").html('Error');
ajaxSent = true;
$("#formElem").submit(); // something like that ....
return false;
} else {
return true;
}
}
});
});

Categories