Controller Action cannot be called from $.Ajax javascript - asp.net-mvc

In MVC, I have written an action in the controller for getting values. The action is as follows..
public void poolshapepdf(List<String> values)
{
...
}
To pass the parameter values to the controller action i pass the values from javascript..
the code is the below,
$.ajax({
type: 'POST',
url: rootDir + "IngroundCalculation/poolshapepdf",
data: { values: collectionPSElmt },
traditional: true,
});
Here collectionPSElmt is an array.
collectionPSElmt[index] = poolshapeValue[index] + "-" + psFeet[index] + "-" + psInch[index];
Here the issue is the controller action cannot be called from the javascript $.Ajax(..).
How do I fix this issue?

You calling the controller by POST and JSON data:
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
}

Now, make a proper call to your url.
specify the data type as json and always go for success function.
using that you can easily crack the report.
$.ajax({
url: '#Url.Action("poolshapepdf", "IngroundCalculation")',
type: "POST",
dataType: 'json',
data: collectionPSElmt ,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("Working..");
}
});
And at Controller Side,
[HttpPost]
public JsonResult poolshapepdf(DataClass[] items)
{
// Your Code here....
}

Related

.NET MVC - Ajax POST not calling .Net MVC method

I'm new to .NET MVC. I'm trying to make an Ajax call to a .NET method, but it doesn't work. Please help.
Here is my Ajax code:
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "userID": $('#confirmation-email-userid').text().toString(), "subject": $('#confirmation-email-subject').text().toString() }),
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
And here is my .Net method in UtilityController:
[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail(string userID, string subject)
{
string destination = db.Users.Where(u => u.Id == userID).Select(u => u.Email).FirstOrDefault();
Task<string> result = new AccountController().SendEmailConfirmationTokenAsync(userID, subject, destination);
return Json(result, JsonRequestBehavior.DenyGet);
}
Try removing the quotation marks in the data parameters of the ajax request
Like this:
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data:
JSON.stringify({
userID: $('#confirmation-email-userid').text().toString(),
subject: $('#confirmation-email-subject').text().toString()
}),
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
Try this, but if you using asp.net mvc, i guess you don't need [WebMethod] attribute
[HttpPost]
[WebMethod]
public JsonResult ResendConfirmationEmail([FromBody] MyModel model)
{
....
}
public class MyModel{
public string userID {get; set;}
public string string subject {get; set;}
}
I think issue with your url where in
use "url: "/Ultility/ResendConfirmationEmail","
insted of "url: "/Utility/ResendConfirmationEmail","
because your controller name is UtilityController
Do not use Webmethod in .net method
No need to use JSON.Stringify in ajax
function resendConfirmationEmail()
{
$("#resend-confirmation-email-status").html('<img src="../../Content/img/ajax-loader.gif" />');
$.ajax({
url: "/Ultility/ResendConfirmationEmail",
type: "POST",
datatype: "json",
contentType: "application/json; charset=utf-8",
data: "{'userID': "+$('#confirmation-email-userid').text().toString()+",'subject': "+$('#confirmation-email-subject').text().toString()+" }",
async: true,
processData: true,
cache: false,
success: function (data) {
$("#resend-confirmation-email-status").html("Email sent");
}
});
}
Remove the [webmothod] data annotation from your action method,
second option you are trying to pass json object for that u dont need to convert into string. Simply pass object
It wil work 👍

Controller in my MVC project returning null from Ajax Post call

I'm not sure to why the controller is receiving a data from an Ajax call . Could i be doing anything wrong?
[HttpPost]
[Route("Product/UpdateDetails")]
public ActionResult UpdateProduct (ProductModel model) <<// model here is null
{
Product p = new Product
{
ProductId = p.ProductId,
Price = p.Price,
};
return View("_ProductDetail"); }
Ajax call below:
var model = {
ProductId: 1,
Price: 270.99,
};
var json = JSON.stringify(model)
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
model: model,
success: function (results) {
}
});
//Model
public class Product
{
public int Id {get;set;}
public double Price {get;set;}
}
Can you guys spot anything that i may be doing wrong in the code above ? I can't see anything that i'm doing wrong.
Try this:
$.ajax({
url: '/Product/UpdateDetails',
type: 'Post',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
You used JSON.Stringify() on your model, but forgot to use the variable "json" on the ajax call, so the ajax was trying to post a "non-json" model.
Also, there is no model setting in ajax calls, the correct one to post your data is data, as you can see here.

IE -10 -Ajax get method not hitting Controller

$http({
method: 'GET',
dataType: 'json',
url: 'Calendar/GetDate',
params: { calenderId: $scope.CalendarId, fyYear: new Date(viewValue).toUTCString()
}
}).success(function (result) {
alert(result);
});
Below value getting returns, and its not calling the controller method
[UMAuthorize]
public ActionResult GetDate(string calenderId, DateTime fyYear)
{
.......
.....
return Json(new { startDate }, JsonRequestBehavior.AllowGet);
}
You are posting data to controller so I guess you should put the attribute HttpPost as shown below :-
[UMAuthorize]
[HttpPost]
public ActionResult GetDate(string calenderId, DateTime fyYear)
{
.......
.....
return Json(new { startDate }, JsonRequestBehavior.AllowGet);
}
and from you are calling controller make it a Post method instead of Get as shown below :-
$http({
method: 'POST',
dataType: 'json',
url: 'Calendar/GetDate',
params: { calenderId: $scope.CalendarId, fyYear: new Date(viewValue)
}
}).success(function (result) {
alert(result);
});
and ur fyYear object is DateTime in controller but you are converting it into string and then sending so its not matching the parameters of controller
I susupect the the url passed is wrong, use Url.Action() helper for generating correct url:
change:
url: 'Calendar/GetDate'
to:
url: '#Url.Action("GetDate","Calendar")'

JQUERY ajax passing null value from MVC View to Controller

hi guys i'm posting some data to controller using jquery ajax, but i am getting null values in my controller,
jQuery code is:
$('#registerCompOff').click(function() {
var compOff = [];
$('div').each(function() {
var curRow = {};
curRow.Description = $(this).find('.reason').val();
curRow.CompOffDate = $(this).find('.datefieldWithWeekends').val();
if (curRow.Description != null && curRow.CompOffDate != null) {
compOff.push(curRow);
}
});
$.ajax({
type: 'POST',
url: this.href,
dataType: 'json',
data: compOff
});
return $('form').valid();
});​
compOff is not null I have checked that...
controller is:
[HttpPost]
public ActionResult RegisterCompOff(RegisterCompOff[] registerCompOff)
{
//return View();
}
can you tell me where i'm going wrong?
Given your original code, change in $.ajax -> data: JSON.stringify(compOff) then add contentType: "application/json; charset=utf-8" and finally change parameter name of controller's action to public ActionResult RegisterCompOff(RegisterCompOff[] compOff). Model binding should kick off then. It did for me.
Edited:
try this :
$.ajax({
type: 'POST',
url: this.href,
dataType: 'json',
traditional: true,
data:
{
CompOffList: compOff
}
});
and change your controller like this :
[HttpPost]
public ActionResult RegisterCompOff(List<RegisterCompOff> CompOffList)
{
//return View();
}
hope this helps
Your r passing javascript object as data wherease jquery ajax method expects a key/value pair list.
Try this
data:{Description:compOff.Description, CompOffDate:compOff.CompOffDate}

How can I RedirectToAction within $.ajax callback?

I use $.ajax() to poll an action method every 5 seconds as follows:
$.ajax({
type: 'GET', url: '/MyController/IsReady/1',
dataType: 'json', success: function (xhr_data) {
if (xhr_data.active == 'pending') {
setTimeout(function () { ajaxRequest(); }, 5000);
}
}
});
and the ActionResult action:
public ActionResult IsReady(int id)
{
if(true)
{
return RedirectToAction("AnotherAction");
}
return Json("pending");
}
I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.
You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)
I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.
C#:
return RedirectToAction("Action", "Controller", new { myRouteValue = foo});
JS:
$.ajax({
type: "POST",
url: "./PostController/PostAction",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (result) {
if (result.responseText) {
$('body').html(result.responseText);
}
}
});
C# worked well
I just changed the JS because responseText was not working for me:
$.ajax({
type: "POST",
url: posturl,
contentType: false,
processData: false,
async: false,
data: requestjson,
success: function(result) {
if (result) {
$('body').html(result);
}
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
You could use the Html.RenderAction helper in a View:
public ActionResult IsReady(int id)
{
if(true)
{
ViewBag.Action = "AnotherAction";
return PartialView("_AjaxRedirect");
}
return Json("pending");
}
And in the "_AjaxRedirect" partial view:
#{
string action = ViewBag.ActionName;
Html.RenderAction(action);
}
Reference:
https://stackoverflow.com/a/49137153/150342

Resources