I am trying to call an ActionResult and update the value of an img on the page based on the returned result from the Action, but for some reason I post to a new page that just prints the string
public ActionResult Favorite(int? id)
{
int PId = Convert.ToInt32(pid);
if (MyDb.CheckExist(Convert.ToInt32(User.Identity.Name),PId))
{
var UF = MyDb.GetExist( Convert.ToInt32(User.Identity.Name),PId);
MyDb.Delete(UF);
MyDb.Save();
return Json(new { Url= "/Content/oldimage.png" }, JsonRequestBehavior.AllowGet);
}
else
{
UFs UF = new UFs();
UF.Id = PId;
UF.UserId = Convert.ToInt32(User.Identity.Name);
UF.CreatedDate = DateTime.Now;
MyDb.Add(UF);
MyDb.Save();
return Json(new { Url= "/Content/newimage.png"}, JsonRequestBehavior.AllowGet);//return favorite image
}
}
my anchor tag that calls my ajax
<a href='<%= Url.Action("Favorite","Home", new { id = item.Id })%>' class="Image" style="text-decoration:none">
<img src="/Content/Images/oldimage.png" alt="FavoriteImage" style="height:25px;width:30px" id="favorite<%:item.Id %>" class="ImageTag" /></a>
$('.Image').click(function () {
var id = this.children('.ImageTag').attr('id');
$.ajax({
url: this.href,
type: 'POST',
dataType: "json",
success: function (data) {
$('#' + id).attr('src', data.Url);
},
error: function (xhr, ajaxOptions, thrownError) {
$.unblockUI();
}
});
return false;
});
and what happens is the action on the server is hit but the page posts to Home/Favorite displaying the returned Json. Home/Favorite is not even a view.
You should prevent the default behavior, the link is making a new request for the Favorite Action refreshing the whole page, getting as response the JSON.
$('.Image').click(function(event) {
event.preventDefault();
//do stuff here
});
Related
I'm working on a .NET Core 3.1 razor pages project, and, on one of my pages, I have an AJAX call on submitting the form details. On clicking the button, I am hitting the post handler and ModelState is valid, but the post is not redirecting to the desired page. I have tried to debug the AJAX call using the devtools and my success and failure functions are not being hit.
Where am I going wrong?
Javascript
$.ajax({
url: "/Candidate/Add?handler=Candidate",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(candidate),
success: function (data) {
//alert('success');
var t = data;
},
failure: function (data) {
var f = data;
}
})
Post handler
public async Task<IActionResult> OnPostCandidateAsync([FromBody] CandidateModel candidate)
{
if (!ModelState.IsValid)
{
IdTypeOptions = idTypeRepository.GetIDTypes().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
industryOptions = industryRepository.GetIndustries().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
GenderOptions = genderRepository.GetGender().Result.Select(g => new SelectListItem
{
Value = g.Id.ToString(),
Text = g.Name
}).ToList();
return Page();
}
//candidateModel.UserId =
var id = await candidateRepository.AddCandidate(candidate);
//return ()
return RedirectToPage("./Index");
}
Any help will be appreciated
ajax call always return some data, or partial view but never redirects inside of the action.
you have to fix on success of ajax
.....
data: ....,
success: function (data) {
window.location.href ...
//or
window.open(....)
},
error: function (jqXHR, exception) {
...error code
}
});
if you want to open another page use
window.location.href = 'http://...;' //the full url of razor page
if you want to open page in another window
window.open('the full url of razor page');
i had to return JsonResult on my post handler and passed the url i wanted to redirect to
public async Task<IActionResult> OnPostCandidateAsync([FromBody] CandidateModel candidate)
{
if (!ModelState.IsValid)
{
IdTypeOptions = idTypeRepository.GetIDTypes().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
industryOptions = industryRepository.GetIndustries().Result.Select(a => new SelectListItem
{
Value = a.Id.ToString(),
Text = a.Name
}).ToList();
GenderOptions = genderRepository.GetGender().Result.Select(g => new SelectListItem
{
Value = g.Id.ToString(),
Text = g.Name
}).ToList();
return Page();
}
//candidateModel.UserId =
var id = await candidateRepository.AddCandidate(candidate);
return new JsonResult("/Candidate/Index");
//return ()
//return RedirectToPage("./Index");
}
and added the window.location.href on to the success function of the ajax call
$.ajax({
url: "/Candidate/Add?handler=Candidate",
type: 'POST',
contentType: 'application/json',
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(candidate),
success: function (data) {
window.location.href = data;
},
failure: function (data) {
var f = data;
}
})
#Serge thank you for your assistance
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);
}
I am trying to get the data of a hidden textbox from the index to a textfield in another view.
First, I get the data using AJAX.
//ajax
if (id && toolcode && shopdoccode) {
$.ajax({
type: 'GET',
url: '#Url.Action("delivery", "service")',
data: { id, memo },
success: function (data) {
if (data.success) {
console.log("Succes");
window.location.href = '#Url.Action("delivery", "service")';
}
},
error: function (data) {
console.log("Error");
}
});
}
window.location.href = ("service/delivery?id=" + id + "&toolcode=" + toolcode + "®date=" + regdate + "&shopdoccode=" + shopdoccode + "&memo" + memo);
}
Then, I make a viewbag in the controller to pass the data to my other view.
public ActionResult Delivery(string id, string memo)
{
ServiceOrder service = GetService(id);
ViewBag.id = id;
ViewBag.memo = memo;
And finally, in the view
#using (Html.BeginForm("GeneratePDF", "Service", FormMethod.Post, new { #class = "form-style-4", id = "getPDFForm" }))
{
string memofield = ViewBag.memo;
//code
<textarea name="jobdescription" readonly>#memofield</textarea>
if I set breakpoints in the controller, I can see that Viewbag.memo contains the correct data. Once in the view I've set a breakpoint on the string memofield = viewbag.memo
Even there, I can see the data. but then, suddenly, if I press continue, the strings are back to 'null'
What am I missing here?
It can happen because after you send ajax request you are redirecting back to Delivery action window.location which does not contain post parameters id and memo.. see
success: function (data) {
if (data.success) {
console.log("Succes");
window.location.href = '#Url.Action("delivery", "service")';
}
}
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',...
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();