Ajax POST int to MVC - javascript

I'm trying to POST an INT with Ajax to my MVC controller.
The script debugging confirms that my variable is an INT with a value (for example 8 and not a string "8"). All lines of code are executed and
I recive my Alert error message.
I've got a breakpoint inside of my Action in the controller but I never get that far. I get a notice in my Action that a request failed, but it only say
"POST Order/Delete". My Controller name is OrderController and Action name is Delete.
My JavaScript:
//Delete order
$(".deleteOrder").on("click", function () {
var id = parseInt($(this).attr("id"));
if (id !== null) {
$.ajax({
url: "/Order/Delete",
method: "POST",
contentType: "application/JSON;odata=verbose",
data: id ,
success: function (result) {
alert("Ok")
},
error: function (error) {
alert("Fail");
}
});
}
});
My MVC Action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
List<OrderRow> lstOrderRow = new List<OrderRow>();
lstOrderRow = db.OrderRows.Where(x => x.OrderId == id).ToList();
foreach(var row in lstOrderRow)
{
db.OrderRows.Remove(row);
}
Order order = new Order();
order = db.Orders.Find(id);
db.Orders.Remove(order);
db.SaveChanges();
return RedirectToAction("index");
}

You should either use the url like this by removing data field
url: "/Order/Delete/" + id,
or send the id in data as below
data: {id: id},

This works for me:data: JSON.stringify({ id: id})
dataType: "json",
contentType: 'application/json; charset=utf-8',

Related

Return parameter null in controller from ajax

I don't know what happened the value sent to the controller is always null, even though in the console.log the value is there, please I need help
this is my ajax:
$('#ddlItemName').change(function () {
var ItemCode = $('#ddlItemName').text();
if (ItemCode != '') {
var RequestParam = {
search: ItemCode
}
console.log(RequestParam);
$.ajax({
url: '/Order/CustomerItemOrders',
type: 'POST',
data: JSON.stringify(RequestParam),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data[0].Name);
},
error: function (data) {
toastr.error(data);
}
});
}
$('#ddlItemName').text('');
});
This is my controller :
[HttpPost]
public JsonResult CustomerItemOrders([FromBody] string search)
{
var result = _order.BindCustomerOrders(search);
return Json(result.data);
}
This is my error :
enter image description here
I've tried adding '[FromBody]' but the value parameter still doesn't get sent
I recomend you add the parameter to query
If you insist on pass the value with request body
Try creat a model:
public class SomeModel
{
public string search{get;set;}
}
in your controller:
public JsonResult CustomerItemOrders([FromBody] SomeModel somemodel)
{
.......
}

Passing parameters in Ajax post back in MVC

I am trying to pass ID parameter from a view to a controller on a click delete link available on a selected row.
Simplified View Layout
#using (Html.BeginForm("#", "Schedule", FormMethod.Post, htmlAttributes: new { #class = "floating-labels" }))
{
#Html.AntiForgeryToken()
Delete
}
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller
namespace Controllers
{
public class ScheduleController
{
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
//do stuff
}
}
}
But on the click of a delete link I get below error and code does not hit controller action.
I am not able to figure out what mistake I am making...
Here is my locally tested implementation that is working.
ScheduleController class:
public class ScheduleController : Controller
{
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Delete(int id)
{
return Ok(id);
}
}
Page that sends the post request:
#Html.AntiForgeryToken()
Delete
<div id="ScheduleList"></div>
<script>
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var uri = '/Schedule/Delete?id=' + id;
var tokenElement = document.getElementsByName('__RequestVerificationToken')[0];
var data = {
__RequestVerificationToken: tokenElement.value
}
$.ajax({
type: "POST",
url: uri,
data: data,
success: function (result) {
success(result);
}
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
The page does nothing but render the html, and the javascript handles the actual Ajax post. What I believe you were missing is the Validation token in your request.
It is because you are not actullay posting the form pass it correctly and add _token in the ajax data list and value for that token will come from #Html.AntiforgeryToken()
reading the error the request is most probably send correctly and there is an internal server error as mentioned in the 500 respond so please check the code that is inside the controller
Try this, you are accesing a javascript variable on c# code, and you cant do that.
If correct, please mark as answer.
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
var url = '#Url.Action("Delete", "Schedule")?id=' + id;
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
data: { id },
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
I think none of the answers above solve the issue. First of all I would replace your target url:
url: '#Url.Action("Delete", "Schedule", new { id = "id" })',
with
url: '#Url.Action("Delete", "Schedule", new { id = actualIdVariable })',
(replace "id" with the actual id variable from the model you're passing to the view).
Note how your browser response is telling you that the url you're posting to is Schedule/Delete/id. That said, I'm not sure you even need the routeValues in this case (the new { id = ...} parameter). this is a POST action, and action parameters wouldn't come from route unless specified by by attribute routing (i.e. [Route("~/Schedule/Delete/{id}")] attribute on your action).
I think your post action is failing because it is trying to parse the "id" string as an int.
Second, I would change the data property of the ajax call and include the anti forgery token. Just because the anchor element you're binding the click event to, is inside the form with #Html.AntiforgeryToken() doesn't mean the generated token will be posted in the ajax request. You're not actually submitting/posting the form, you're just clicking a button.
it should be something like
data: {
'id': id,
'__RequestVerificationToken': $('[name="__RequestVerificationToken"]').val()
}
try this, it solve the error on routing (different url Action) and the parameter on the controller:
JavaScript
<script type="text/javascript">
function DeleteSchedule(id) {
if (confirm('Are you sure you want to delete this Schedule?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Schedule")',
data: "id=" + id ,
async: true,
cache: false,
success: function (result) { success(result); }
});
}
return false;
}
function success(result) {
$("#ScheduleList").html(result);
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(string id)
{
//do stuff
}
Nicola.

Ajax POST an object with javascript, but the value in backend is null, why?

So on button click there is a function sendEmail(). Alert is working fine, I can see my datas there. But on backend I can't see anything, just everything is null.
function sendEmail() {
var datas = new Object();
datas.mail = $('#contactDropdownList').val();
datas.mailobject = $('#emailObject').val();
datas.text = $('#emailText').val();enter code here
alert(datas.mail + datas.mailobject + datas.text);
$.ajax({
type: "POST",
dataType: "json",
url: "/Email/sendEmail",
contentType: 'application/json; charset=UTF-8',
data: JSON.stringify({ items: datas }),
success: function (data) {
console.log(data);
//do something with data
},
error: function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
}
});
}
C# code:
public class MyClass
{
public string Email { get; set; }
public string Object { get; set; }
public string Text { get; set; }
}
[HttpPost]
public IActionResult sendEmail(MyClass items)
{
return Json(new { data="Ok" });
}
items.Email, items.Object and items.Text are null.
And the return valu is null as well, because in javascript success: function (data) { console.log(data);
is empty string.
What can be the problem? Thank you!
Model binder expects json content to match C# class. Your datas object should look like that
var datas = {
email: $('#contactDropdownList').val(),
object: $('#emailObject').val(),
text: $('#emailText').val()
}
Since you wrapped your object ({ items: datas }), you may think it will be mapped to sendEmail(MyClass items), but in reality items name does not matter, you can change variable name to any other name you like
Make sure you apply [FromBody] attribute to your parameter like that
[HttpPost]
public IActionResult sendEmail([FromBody]MyClass items)
Complete demo:
<script>
function sendSmth() {
var data = {
Email: 'email',
Object: 'object',
Text: 'text'
};
$.ajax({
type: "POST",
dataType: "json",
url: "/home/index",
contentType: "application/json",
data: JSON.stringify(data),
success: function (datas) {
console.log(datas)
}
})
}
</script>
And controller
[HttpPost]
public IActionResult Index([FromBody]MyClass obj)
{
return View();
}
As someone has noted, you have a mismatch between what you're sending to the controller and what the model the modelbinder is expecting. You can also vastly simply your AJAX code:
function sendEmail() {
var data = {
Email: $('#contactDropdownList').val(),
Object: $('#emailObject').val(),
Text: $('#emailText').val()
};
$.post("/Email/sendEmail", data)
.done(function (response) {
console.log(response);
//do something with response
})
.fail(function (jqXHR, textStatus, error) {
//log or alert the error
console.log(error);
});
}
You don't really need to specify the content type or data type - the $.post helper's defaults work just fine for what you've shown.

JsonResult takes only the first parameter and ignores the rest

I am having a strange issue that is up above my level, I tried to troubleshoot the issue without luck.
I am developing a simple MVC application and I am using ajax to send data from a view to controller. For some reason, the controller only recognized the fist parameters and the rest are just nulls. I even tried to put fixed strings instead of variables but they still appear as null from the controller???
The view:
$.ajax({
type: "POST",
url: "../Home/AddItem",
data: "{ItemModel: 'ttt1', ItemName: 'ttt2'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(JSON.stringify(data));
if (data.Success == "Success") {
alert("Item has been added.");
} else {
alert("We were not able to create the offer");
}
},
error: function (exception) {
console.log(exception);
}
});
On the Home controller, I have the below action:
[HttpPost]
public JsonResult AddItem(string ItemModel, string ItemName)//ItemName is always null??
{
try
{
_DB.Database.ExecuteSqlCommand(#"INSERT INTO ITEMS(iModel, iName) VALUES ({0}, {1})", ItemModel, ItemName);
return Json(new { Success = "Success" });
}
catch (Exception ex)
{
throw ex;
}
}
You are not sending the data correctly.
The code indicates JSON but is sending just a single string. If you inspect ItemModel, I am certain it will contain the string data sent from the client.
Create a JavaScript object and then stringify that as the body of the request.
var payload = { ItemModel: 'ttt1', ItemName: 'ttt2' }; //<-- create object
$.ajax({
type: "POST",
url: "../Home/AddItem",
data: JSON.stringify(payload), //<-- properly format for request
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(JSON.stringify(data));
if (data.Success == "Success") {
alert("Item has been added.");
} else {
alert("We were not able to create the offer");
}
},
error: function (exception) {
console.log(exception);
}
});
The model binder should then be able to differentiate the desired parameters.
Ideally when expecting data in the body of a request it is better to use a model
public class Item {
public string ItemModel { get; set; }
public string ItemName { get; set; }
}
And have the action explicitly look for it in the body of the request using the FromBody attribute
[HttpPost]
public JsonResult AddItem([FromBody]Item item) {
if(ModelState.IsValid) {
try {
var sql = #"INSERT INTO ITEMS(iModel, iName) VALUES ({0}, {1})";
_DB.Database.ExecuteSqlCommand(sql, item.ItemModel, item.ItemName);
return Json(new { Success = "Success" });
} catch (Exception ex) {
throw ex;
}
}
return Json(new { Success = "BadRequest" });
}

getting null value in list when passing by ajax call to mvc controller

I am passing my list to an mvc controller but I am getting null value in the controller.But my list has values when show in alert on client side.
ajax call
$("#addTiles").click(function() {
userTiles = JSON.stringify({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "GET",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
mvc controller
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
List Model
public class UserTilesVM
{
public int TileID { get; set; }
public int TopPosition { get; set; }
public int LeftPosition { get; set; }
}
List in javascript
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
I have also tried by sending my list with stringfy but that also doesn't work.
Use : [HttpGet] on the method AddTiles as you have used type: "GET" on the Ajax hit.
[HttpGet]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
If Still doesn't works then try type: "POST" on Ajax hit and on method use [HttpPost]
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
You have contentType and dataType twice in your AJAX setup, with different values, which will break the AJAX call.
Keep in mind contentType is to tell the server what type of data to expect and dataType is to determine what type of data is returned, from the documentation.
Edit: I see you have edited your code!
In this case, since you are using JSON.Stringify to modify the data you are sending, you would use contentType: "application/json; charset=utf-8", as your contentType, since you are sending JSON data to the backend.
when we are trying to pass object data using ajax, we have to store data in variable and pass data directly using "data :'variable'" in AJAX to Controller Method
$("#addTiles").click(function() {
var userTiles = ({
'userTiles': userTiles
});
alert("Entered function.");
alert(userTiles[0].TileID);
var url = '#Url.Action("AddTiles")';
$.ajax({
type: "POST",
url: url,
data: userTiles,
success: function(d) {
if (d.indexOf('"IsSessionExpired":true') != -1) {
location.reload();
} else {
onAddTilesSuccessful(d);
}
},
error: function() {
errorInOperation();
},
contentType: "application/html; charset=utf-8",
dataType: 'html'
});
});
function onAddTilesSuccessful(e) {
$("#tilesSubmissionMsg").append(e);
}
function errorInOperation(d) {
$("#tilesSubmissionMsg").append("Something went wrong");
}
//Use [HttpPost] keyword for getting value which was passed by AJAX.
[HttpPost]
public ActionResult AddTiles(List<UserTilesVM> userTiles)
{
return View();
}
I think your list definition is not ok:
"{"userTiles":[{"TileID":"3","TopPosition":0,"LeftPosition":0}]}"
should be:
"{"userTiles":[{"TileID":"3","TopPosition":"0","LeftPosition":"0"}]}"
i have using this sequence that work fine
you have check the
contentType: "application/json",
dataType: "json",
sequence in ajax method

Categories

Resources