Jquery Ajax and MVC5 httpPost no value received - javascript

I try to send values from my view to my controller.
The method in my controller is called but the value(s) still remain NULL.
Here is the Javascript part:
GUIRequests.prototype.SetNewItemDeliveryValues = function () {
var modelNumberID = this.GetValue('#ModelNumberID');
this.Request.GetPreOrderIDForModelNumberID(modelNumberID); //InventValueRequest
this.Request.GetShortfallAndOverdeliveryInNewItemDelivery(modelNumberID);
}
InventValueRequest.prototype.GetPreOrderIDForModelNumberID = function (_modelNumberID) {
this.CallAjax("/NewItemDelivery/GetPreOrderIDForModelNumberID", _modelNumberID, CallbackMethods.SetPreOrderID);
}
//Private
InventValueRequest.prototype.CallAjax = function (_url, _data, _successFunctionPointer) {
$.ajax({
type: 'POST',
url: _url,
contentType: 'application/json',
data: JSON.stringify(_data),
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
}
Asp.Net MVC5 (C#) part
[HttpPost]
public ActionResult GetPreOrderIDForModelNumberID(string _modelnumberID)
{
String preOrderID = "";
if (_modelnumberID == null)
{
preOrderID = "No value received";
}
else
{
//Do something
}
return Json(preOrderID);
}
What could be the problem with my code ? why don't I receive any values in my C# part ? It seems that the values get send correctly, at least the payload contains the values I would expect.

_data should have the property _modelnumberID like following.
_data = {'_modelnumberID': '1'}

try below code :
$.ajax({
type: 'POST',
dataType: 'text',
url: _url,
contentType: 'application/json',
data: "_modelnumberID=" + _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});

The Ideal solution would be to use a view model.
public class Create
{
public string _modelnumberID{get;set;}
}
And your HttpPost action would be accepting an object of this
[HttpPost]
public ActionResult View(Create model)
{
// do something and return something
}
and ajax will be
$('.submit').click(function () {
var myData = {
_modelnumberID: _data
}
$.ajax({
url: '/Controller/Action',
type: 'POST',
data: myData,
processData: false
}).done(function () {
}).fail(function () {
});
});

$.ajax({
type: 'POST',
url: _url+"?_modelnumberID="+ _data,
success: _successFunctionPointer,
error: InventValueRequest.HandleError
});
Try this.

Related

Why it value does not send in to ajax post?

I'm a newbie working with ajax. I have a problem while sending the data into ajax post.
The output of console.log(obj.Id) and console.log(oke) is 2. Then I tried to send it through data in ajax, but it end up 0 in the controller.
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: oke,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
And my controller looks like this
[HttpPost]
public JsonResult Details(int id)
{
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
I want the '2' value that passes into my controller, how can I do that? Thank you for your help.
An alternative way to send your data your Controller method using Ajax would be to wrap your data in a JSON object and then send it to the server for processing. The server will be then deserialize your JSON object and you can access the required properties from that process:
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
var json = {
oke: oke
};
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: {'json': JSON.stringify(json)},
type: 'POST',
dataType: "json",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
And your Controller method will be:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult Details(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id= Convert.Int32(jsondata["id"]);
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
If you just need id in your method parameter just change data in ajax to:
contentType: "application/x-www-form-urlencoded",
data: { 'id': oke },
id is name of parameter from controller method.
Please change the data property in ajax part.
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: { 'id': oke },
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});

Pass json from js to controller

Data doesn't passing to controller, always null
My script in view:
function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: { "json": JSON.stringify(selected) },
error: function () {
alert("Error!");
}
});
}
My home controller method:
[HttpPost]
public IActionResult DeleteRecords(string AllId)
{
return null;
}
send ajax request data like below,
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(selected),
error: function () {
alert("Error!");
}
});
and receive the data in action like
[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
return null;
}
It need to pass the action. Hope it helps to you.
with the code in your question, try below to get the json
System.Web.Context.Current.Request.Form["json"]
if you want some more graceful stuff, you need to put FromBody attribute in your parameter signature
DeleteResults([FromBody] string json)
Name your property in the Post the same as your method so that the automatic binding picks it up. - Turns out this doesn't matter for single object.
The data Object you were creating was not parse-able by .net, use JSON.stringify directly for the data payload.
Note: The change in Home controller since you are passing an array of string.
function deleteRecords() {
var selected = [];
$('#myTable input:checked').each(function () {
selected.push($(this).attr('id'));
});
$.ajax({
url: '/Home/DeleteRecords',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(selected),
error: function () {
alert("Error!");
}
});
}
For your home controller method:
[HttpPost]
public IActionResult DeleteRecords(string[] AllId)
{
return null;
}

Jquery Function always return count 0 of second parameter

i am writing a function in jquery which post the data to controller. currently it is posting form data to controller fine but when i post checkbox list with form data then it send always count 0 in controller here is my code.
function SubmitForm() {
var studentFormData = $("#frmStudent").serialize();
debugger;
var SubjectArraydata = new Array();
$(".chkSubject:checked").each(function () {
var row = {
"SubjectId": $(this).data("id")
};
SubjectArraydata.push(row);
});
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
async: true,
success: function (msg) {
},
error: function () {
}
});
}
Controller:
[HttpPost]
public ActionResult StudentForm(Student student, List<Subject> subjectData)
{
return Json(true);
}
any one tell me where is the problem in my code thank you.
Your cannot mix 'application/x-www-form-urlencoded' data (the contentType of your serialize() method) and 'application/json' data (the contentType of the JSON.stringify() method) like that.
Sinve you have confirmed that your only submitting one property of Subject, which is SubjectId and is typeof int, then you can append the SubjectId values to the serialized data.
var studentFormData = $("#frmStudent").serialize();
$(".chkSubject:checked").each(function () {
studentFormData += '&' + $.param({ SubjectIds: $(this).data("id") });
};
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData,
success: function (msg) {
},
error: function () {
}
});
and change your controller method to
[HttpPost]
public ActionResult StudentForm(Student student, List<int> SubjectIds)
{
....
I think you use 'POST' method not correctly. You try to mix sending data as json and as url parameters.
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
what you send in data:
[
{...},
[{SubjectId: ''}, {SubjectId: ''}]
]
or:
{
1: {...},
subjectData: [{SubjectId: ''}, {SubjectId: ''}]
}
or some data sended as json, some in url?
Send all data in json, and dont serialize (jquery do it for you):
var data = [strudentFormData, subjectData];
$.ajax(..., data: data, ...);

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

How to pass a list of id's in a AJAX request to the Server in MVC

In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?
I accept with or without use of Html helpers.
I know MVC's model binder has no problem when it comes to simple types like int, string and bool.
Is it something like I have to use and array instead in the action?
I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server.
My List ids gives null at the moment.
Javascript:
var ids= [1,4,5];
// ajax request with ids..
MVC Action:
public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
// build model ect..
return PartialView(model);
}
EDIT: Added my AJAX request
$(document).ready(function () {
$('#spanComputerPackagesBuffer').on('click', function () {
var ids = $('#divComputerPackagesBuffer').data('buffer');
console.log('bufferIds: ' + bufferIds);
var data = {
ids: ids
};
var url = getUrlShowComputerPackageBuffer();
loadTable(url, "result", data);
});
});
// AJAX's
function loadTable(url, updateTargetId, data) {
var promise = $.ajax({
url: url,
dataType: "html",
data: data
})
.done(function (result) {
$('#' + updateTargetId).html(result);
})
.fail(function (jqXhr, textStatus, errorThrown) {
var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
alert(errMsg);
});
};
// URL's
function getUrlShowComputerPackageBuffer() {
return '#Url.Action("ShowComputerPackageBuffer", "Buffer")';
};
SOLUTIONS: // Thanks to #aherrick comment. I missed the good old "traditional"
$.ajax({
type: "POST",
url: '#Url.Action("ShowComputerPackageBuffer", "Buffer")',
dataType: "json",
traditional: true,
data: {
bufferIds: bufferIds
}
});
Use the traditional parameter and set it to true.
$.ajax({
type: "POST",
url: "/URL",
dataType: "json",
traditional: true,
data: {}
});
Try this one (I've checked it):
$(function () {
var ids = [1, 4, 5];
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '#Url.Action("YourAction", "YourController")',
data: JSON.stringify( { ids: ids })
}).done(function () {
});
});
You have to make sure your contentType is application/json and your data is stringified.
public ActionResult SaveSomething(int[] requestData)
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)
Using Action Result you cannot receive JSON object:
Using Controler:
[HttpPost]
[Route( "api/Controller/SaveSomething" )]
public object SaveTimeSheet( int[] requestData )
{
try
{
doSomethingWith( requestData );
return new
{
status = "Ok",
message = "Updated!"
};
}
catch( Exception ex )
{
return new
{
status = "Error",
message = ex.Message
};
}
}
java script:
var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
url: baseUrl + '/api/Controller/SaveSomething',
type: 'POST',
data: JSON.stringify(ids),
dataType: 'json',
contentType: 'application/json',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
if (result != undefined) {
window.location.href = window.location.href;
}
},
async: false,
});

Categories

Resources