JQuery values passed to WebApi is always null - c#

I am having trouble with Web Api and was hoping someone here might be able to help me.
I have a jQuery method as follows ...
function OnInsert(evt) {
var truckId = $("#txtTruckId").val();
var truckReg = $("#txtTruckReg").val();
var description = $("#txtDescription").val();
var condition = $("#txtCondition").val();
var data = '{"obj":{"TruckId":"' + truckId + '","Reg":"' + truckReg +
'","Description":"' + description + '","Condition":"' + condition + '"}}';
var json = JSON.stringify(data)
$.ajax({
url: '/api/Values',
cache: false,
type: 'POST',
data: json,
dataType: 'json',
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
})
}
When I debug that the 'data' variable successfully captures the data.
I then have a function in my WebApi controller ...
// POST api/values
public void Post(TruckInfo obj)
{
WebApiTestEntities db = new WebApiTestEntities();
db.TruckInfoes.Add(obj);
db.SaveChanges();
}
However, when I debug thst all of the parameters are showing a null value.
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but that hasn't worked.
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
I also found this which kind of comes up with an answer but after trying to alter my code so it looks like the code they have written it still doesn't work.
jQuery posts null instead of JSON to ASP.NET Web API
Is any one able to help?
Thanks in advance
Lex

Start by fixing your JSON:
var data = {
truckId: truckId,
reg: truckReg,
description: description,
condition: condition
};
var json = JSON.stringify(data);
and then make sure you specify the correct content type request header:
$.ajax({
url: '/api/Values',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: json,
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
});
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but
that hasn't worked.
No, no, no. Not necessary as long as you format properly your JSON request, the Web API will bind it to your model.

Related

HttpContext.Request.Form.Keys is empty when HttpContext.Request.HasFormContentType = true

This was working 2 days ago and now it's not and I cannot figure out why. I am submitting form data via ajax:
var mData = 'item=' + itemid + '&action=' + action;
$.ajax({
url: "/Admin/Home/Ajax",
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: mData,
success: function (data) {
//Do Something
}
});
I have a method that process the incoming post:
if (HttpContext != null && HttpContext.Request.HasFormContentType)
{
foreach (var key in HttpContext.Request.Form.Keys)
{
QueryParams.Add(key, HttpContext.Request.Form[key]);
}
}
When the data is posted, HttpContext.Request.HasFormContentType is equal to true however, HttpContext.Request.Form.Keys.Count is equal to 0
I get no errors or anything. Any help or insight as to what is going on would be greatly appreciated.
This is a dotnet core 2.2 mvc web app.
Here is a working demo like below:
1.View:
<script>
var mData = 'item=' + 1 + '&action=' + "aaa";
$.ajax({
url: "/Home/Ajax",
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: mData,
success: function (data) {
//Do Something
}
});
</script>
2.Action:
[HttpPost]
public void Ajax(int item,string action)
{
if (HttpContext != null && HttpContext.Request.HasFormContentType)
{
foreach (var key in HttpContext.Request.Form.Keys)
{
}
}
}
3.Result:
You are sending query data, not form data. Try sending it in a form like:
{
item: ...,
action: ...
}
Edit: Actually I was a bit surprised that it works while sending raw type of data and then passing in the query-like string. But the mearly fact that it works it doesn't mean it is a proper way of doing things. Foe example if You try to send API request from Postman (which I tried to reproduce Your error) I wasn't even able to perofrm such a thing as Postman asked me for key value pairs and interpreted a given query as a one key. Besides sending js object is more simpler that building a string.
I was also facing the issue of HttpContext.Request.Form.Keys is empty.
I just removed the .aspx extension from the request page and now the problem seems to be resolved for me.

ajax post data is null in controller asp.net mvc 5

I try to send a JSON object back to the server. This is my AJAX call
function SaveData() {
var model = []
debugger
$.each($('.Money'), function (i, item) {
model.push({
Money: $('.Money').eq(i).val(),
Day: $('.Day').eq(i).val(),
Note: $('.Note').eq(i).val()
});
})
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: { partnerDeposit: JSON.stringify(model) },
type: 'POST',
dataType: 'json',
succsess: function () {
}
})}
This is the method in the controller which is being called:
enter image description here
https://i.stack.imgur.com/FqEt9.png
The problem I have is that always the json variable from above is an empty object. The success function gets called but when I debug the json var is displayed as empty.
Please tell me what I am doing wrong. Thank you.
Try adding the partnerDeposit to the JSON.stringify call like this:
$.ajax({
url: '#Url.Action("Create")',
contentType: "application/json",
async: true,
data: JSON.stringify({partnerDeposit: model}),
type: 'POST',
dataType: 'json',
succsess: function () {
}
})
I haven't found this answer anywhere else so I had to discover it through experimentation. Hopefully this will help someone.
You'll find that in your controller, it's receiving a Request.Form object and if you look in Request.Form[0] you'll find your data. The reason that there's data in the form but MVC is seeing it as null is that the key to the form element being POSTed is "" (blank).
So client side, you have to set content type properly, and precede your data with something like "myData=" + JSON.stringify(myJSONObject), where "myData" is the key name you are adding, like so:
$.ajax({
type: "POST",
url: URL,
data: "myData="+JSON.stringify(myJSONObject),
contentType: "application/x-www-form-urlencoded; charset=utf-8"
On the server side, your [HttpPost] endpoint has to have as its input a variable with the same name as the key you declared in your AJAX, like so:
`
[HttpPost]
[Authorize]
public ActionResult Index (string myData) // <-- var name matches AJAX
{
// de-serialize data into server-side object using
// JSONConvert.DeserializeObject
}
`

MVC Send list through AJAX

Okay, I've seen tons of questions posted regarding this question, but none of the answers has actually worked for me, here's my AJAX:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data: jsonFilters,
traditional: true,
success: function (response) {
//Haha, it's never entering here. not really.
}
});
var "jsonFilters" contains an array with the following data:
[0] = { Path: "Test", Name: "More testing", Value: "Test Value" },
[1] = { Path: "Test", Name: "More testing", Value: "Test Value" }
And this is my controller:
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
jsonFilters always remains null... I have also tried adding contentType: "application/json; charset=utf-8" to the AJAX call... but that didn't really do anything
Finally, the class FilterSessionModel is structured as follows:
public class FilterSessionModel
{
public string Path { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
Any ideas as to what I might be missing or what might be happening?
Things I've tried so far:
Setting "traditional: true", setting "contentType", using JSON.stringify and attempting to accept a string in the MVC Controller (no-go)
UPDATE: Thanks to the answer below I realized that what was missing was to send over the data with the param Id like so:
data: "{param1ID:"+ param1Val+"}"
I would try switching out the type on your action.
List<FilterSessionModel>
Pretty sure the above is not going to work, I would try something like Object.
Or possibly a string that I would then use newton json dll to push into your List of Class.
The problem boils down to your action being unable to figure out the type, assuming you are checking your data prior to the ajax get being called.
**Update due to more info. Add in the error portion and view those vars on return from your controller, also fire up fiddler and watch what your are getting for http numbers.
$.ajax({
type: "POST",
url: "Servicename.asmx/DoSomeCalculation",
data: "{param1ID:"+ param1Val+"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
UseReturnedData(msg.d);
},
error: function(x, t, m, b) {
//Look at the vars above to see what is in them.
}
});
I think what you are looking for is answered here:
Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax
First off I'm making the assumption that your $.ajax is for JQuery and not some other Javascript framework. Please correct me if that's wrong.
ASP.NET MVC can actually do what you are asking it to (resolve data sent via AJAX to a List<FilterSessionModel>, but it seems to have a difficult time doing it via a GET request. It would help to know which version of ASP.NET MVC you are using, as more is required to get this working on the older versions. However, what I'm suggesting should work on MVC 3 or 4.
When you send AJAX via JQuery using a GET request and passing it a JavaScript array, this is what you are sending to the server:
http://localhost:50195/FilterSessions/GetFilterSession?undefined=&undefined=
It's no wonder the model is null because no data is actually being sent.
I believe ASP.NET can accept objects (and even arrays of objects) like this, but it won't do so with it formatted as JSON (like via JSON.stringify) as that just results in the following request:
http://localhost:50195/FilterSessions/GetFilterSession?[{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22},{%22Path%22:%22Test%22,%22Name%22:%22TestName%22,%22Value%22:%22Testing%22}]
The way you probably want to do this is with a POST request. ASP.NET MVC will actually accept a JSON string as POST data and will decode it and resolve the model properly. Your AJAX code works fine with a couple modifications:
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "POST", //Changed to POST
dataType: "json",
data: JSON.stringify(jsonFilters), //Pack data in a JSON package.
contentType: "application/json; charset=utf-8", //Added so ASP recognized JSON
traditional: true,
success: function (response) {
alert('Success!');
}
});
The controller you posted should recognize POST data already, but in case it doesn't, a simple [HttpPost] attribute is all you need:
[HttpPost]
public ActionResult GetFilterSession(List<FilterSessionModel> jsonFilters)
{
//Do things
return Json(false, JsonRequestBehavior.AllowGet);
}
javascript or ajax call never type cast the object. . .you need to set type of the controller side parameter either string or List else you can also set the Object type. . If you modified codein that way.. .Your code definitely work !!!
$.ajax({
url: "/FilterSessions/GetFilterSession",
type: "GET",
dataType: "json",
data:JSON.stringify({ 'jsonFilters': jsonFilters}),
contentType: 'application/json; charset=utf-8',
success: function (response) {
//Do your action
}
});

unable to pass post value over from ajax to the page in .net c#

Does anyone know what is it going on here? I have try to pass a value from ajax to .aspx, but somehow the value seem doesn't pass over successfully.
Following is my code:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: "sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
and this is my code inside my .net c#:
newTest.Value = Request.QueryString["sState"];
Somehow the for Request.QueryString["sState"] is empty in .net c#. Does anyone know what is going wrong here ?
When passing data in POST, the data is not passed in Request.QueryString, it's passed into Request.Form instead. Try
newTest.Value = Request.Form["sState"];
Another thing I'd change is the jQuery call - use a data object instead of just a string, a such:
$.ajax({
type: "POST",
url: "pgtest.aspx",
data: { sState: "VIC" },
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Request.QueryString is for GET requests only. For POST requests, you need Request.Form. See also: Get POST data in C#/ASP.NET
You need to use GET request as it is light in nature but less secured too and it is passed in querystring.:
$.ajax({
type: "GET",
url: "pgtest.aspx?sState=VIC",
success: function (msg) {
alert("Data Saved: " + msg);
}
});
Now you will get below values:
newTest.Value = Request.QueryString["sState"];

$.Ajax POST, accessing return data

I'm currently working on a ASP.NET Webforms site and I've run in to a small problem. Been searching around for 2 hours now and I got a deadline, so hoping someone here can assist.
On my .cs file I have the following Webmethod
[WebMethod]
public static string IsJobEditable(int jobid)
{
try
{
string isEditable = "false";
JobsBLL jbl = new JobsBLL();
int jobStatusId = jbl.GetJobStatusId(jobid);
if(jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Waiting) || jobStatusId == Convert.ToInt32(ConstantsUtil.JobStatus.Edit))
{
isEditable = "true";
}
return isEditable;
}
catch (Exception ex)
{
throw ex;
}
}
This function in this case will ALWAYS return TRUE as a string.
On Aspx page I have the following
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (result) {
alert(result);
// This is written out in the alert {"d":"true"}
// I want this in a variable as a string
// so I can do a check on it before I do some other actions
// The format is not a String so i cannot split on it to
// retrieve the "true" part.
},
error: function (err, result) { alert(err); }
});
});
As you can see in the comments the value I get back in the Callback method is in to me a weird format. The type is unknown and I need this value to be able to proceed with my entire method surrounding the small portion of the Javascript.
So can anyone point me into the direction where I can access the result variable / data as a var or anything else that will let me put it into a var (as a string).
Use result.d to get your string.
See this site for an explanation of the .d issue when calling .ajax from ASP.NET: http://encosia.com/2009/02/10/a-breaking-change-between-versions-of-aspnet-ajax/
try alert(result.d);
You can easily retrieve the "true" part like this:
alert(result.d);
The reason the object is wrapped in the "d" json object is security. You can read about it for example here.
According to two articles I found, I think you want to specify "DataType" as json not as text (since you're expecting a content-type of json to be returned). That may be your issue, though i don't have a sample project in front of me to test on. Your result is also probably result.d as outlined in those same articles.
This solved it:
$(function () {
$.ajax({
type: "POST",
url: "Coordination.aspx/IsJobEditable",
data: "{jobid:" + jobid + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
//I finally got the data string i wanted
var resultAsString = result.d;
},
error: function (err, result) { alert(err); }
});
});
So 2 things were done to solve this. I had to change the dataType to "json" and I used the result.d to retrieve my data.
What threw me off was the lack of intellisens on the result object. But the .d (data) property however solved it.
Thanks you to all who contributed to this answer.

Categories