.NET MVC - Ajax POST not calling .Net MVC method - asp.net-mvc

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 👍

Related

MVC Model properties are null when calling post mvc action via ajax call

I have below lines of code in controller, model and in js file.
I am able to make call to controller, but model properties are always null.
...
[HttpPost]
public IActionResult CreateBooking(Country request)
{
return Ok();
}
public class Country
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("code")]
public string Code { get; set; }
}
var request = {
name: 'Prateek',
code: 'US'
};
$.ajax('/Home/CreateBooking', {
data: JSON.stringify({ request }),
contentType: 'application/json',
type: 'POST',
dataType: 'json',
success: function (response) {},
error: function(response){}
Can anyone help please?
Thanks in advance
var request = jQuery.parseJSON('{ "Name": "Prateek", "Code": "US" }');
$.ajax({
url: "/Home/CreateBooking",
type: "POST",
dataType: "JSON",
data: request,
success: function (d) {
},
error: function (d) {
console.log(d);
}
});

Controller Action cannot be called from $.Ajax javascript

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

Received parameter from ajax POST empty in controller + passed parameter in firebug MVC 4

I have looked over the net to figure out what my mistake is. All suggestions I found I tried, without any succes. I access the httppost action in my controller but the parameters stays empty.
AJAX function
var dataPost = { 'id': id, 'val': val };
debugger;
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: dataPost ,
contentType: 'json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
On debug DataPost is populated.
Controller
[HttpPost]
public ActionResult UpdateJson(string id, string val)
{
//do stuff
return Json(true);
}
The parameters I used in my controller have the same name as in my Ajax function. The format passed is json, I have also tried populating my data with:
var dataPost = { 'id': 'id', 'val': 'val' };
But this doesn't make any difference. I have also tried to work with a Class, like -->
Class
public class ScheduleData
{
public string id { get; set; }
public string val { get; set; }
}
Controller
public ActionResult UpdateJson(ScheduleData data)
{//Do something}
Any help would be appreciated. Thanks in advance
The format passed is json
No, not at all. You are not sending any JSON. What you do is
data: { 'id': id, 'val': val }
But as the documentation clearly explains this is using the $.param function which in turn uses application/x-www-form-urlencoded encoding.
So get rid of this contentType: 'json' property from your $.ajax call.
Or if you really wanna send JSON, then do so:
var dataPost = { 'id': id, 'val': val };
$.ajax({
type: 'POST',
url: '/Extensions/UpdateJson',
data: JSON.stringify(dataPost),
contentType: 'application/json',
success: function () {
alert("succes");
},
error: function () {
alert("error");
}
});
Things to notice:
usage of JSON.stringify(dataPost) to ensure that you are sending a JSON string to the server
contentType: 'application/json' because that's the correct Content-Type value.

MVC bind Json collection of objects to controller action

is there a way to send a collection of objects to MVC action?
View:
$(".iconDocumentText").click(function (e) {
e.preventDefault();
var $inputs = $("form.form :input:not('.submit')");
var values = {}; // get search form values
$inputs.each(function () {
if ($(this).val()) {
values[this.name] = $(this).val();
}
});
console.log(JSON.stringify(values));
$.ajax({
url: "#Url.Action("Export","Log")",
data: JSON.stringify(values),
contentType: 'application/json',
type: 'GET',
success: function (data) {
.........
}
});
});
I tried this without any luck:
public ActionResult Export(Dictionary<string, string> values)
{
....
this is what's being sent to controller action:
{"f_device":"4","f_package":"AGI-VS-GAME-M52-1.5.3.2.67"}
You have also to indicate that it is of datatype json and pass them directly:
Script :
$.ajax({
url: "#Url.Action("Export","Log")",
data: values,
contentType: 'application/json',
type: 'GET',
dataType: 'json'
});
Controller :
public ActionResult Test(int f_device, string f_package)
{
EDIT :
But if you want to retrieve a dictionary, you can encapsulate your data in an object :
Script :
$.ajax({
url: "#Url.Action("Export","Log")",
data: { values : values },
contentType: 'application/json',
type: 'GET',
dataType: 'json'
});
Controller :
public ActionResult Test(Dictionary<string, string> values)
{

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}

Resources