MVC 4 APIController not receiving POST data - javascript

Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.

Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.

Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});

Related

Sending JSON string to my backend code to add it to my DB but it's not adding anything

I've been stuck on this problem for a good bit
I'm trying to add an object to my database through jQuery/AJAX. Apparently, there are no errors but it's not adding anything to my DB.
This is my JS/JQuery code:
var student = new Object();
student.Name = $("#txtNameAdd").val();
student.Age = $("#txtAgeAdd").val();
student.Email = $("#txtEmailAdd").val();
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
alert(response.responseJSON);
}
});
My JS code points towards this code I have in my Default.aspx page code:
[WebMethod]
public static void AddStudent(string studentJSONString)
{
JavaScriptSerializer converter = new JavaScriptSerializer();
Student a = converter.Deserialize<Student>(studentJSONString);
WebMethods.AddStudent(a);
}
Which points to this code in my WebMethods.cs class
[WebMethod]
public static void AddStudent(Student student)
{
MasterStudent master = new MasterStudent();
master.AddStudent(student);
}
And finally that goes to my class library and finishes with this method in MasterStudent:
public void AddStudent(Student student)
{
if (string.IsNullOrWhiteSpace(student.Name))
{
throw new Exception("There's no name");
}
if (string.IsNullOrWhiteSpace(student.Email))
{
throw new Exception("There's no email");
}
using (studentEntities model = new studentEntities())
{
model.student.Add(student);
model.SaveChanges();
}
}
I run the code and the Console doesn't log any problems but it also doesn't do anything.
I have run very similar code on a Forms application with no problems so I'm kind of in a pickle right now. Does anyone know why it keeps failing?
Have you tried attaching a debugger to it and verifying that the student object is not null prior to model.SaveChanges() ?
Try debugging and verifying that the student string is being converted to an actual Student object first.
If it is, then try profiling the DB and validate any commands issued.
So I actually did find a solution shortly after posting my question, I changed my JQuery AJAX call to look like this:
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
$("#lblErrorAdd").text(response.responseJSON.Message);
$("#lblErrorAdd").css("display", "block");
}
});
And it actually works now! so either the dataType or contentType were very important for what I was trying to do
Thanks for your answers everybody
var student = new Object();
student.Name = $("#txtNameAdd").val();
student.Age = $("#txtAgeAdd").val();
student.Email = $("#txtEmailAdd").val();
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: student,
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
alert(response.responseJSON);
}
});
Then you can to point to this WebMethod.
[WebMethod]
public static void AddStudent(Student student)
{
MasterStudent master = new MasterStudent();
master.AddStudent(student);
}
Try this.

Calling [HTTPPost] from Javascript ASP.NET

I am using a method in my controller which imports data from an API. This method I am wanted to be called from two locations. First the view (currently working) and secondly a javascript function.
Start of controller method:
[ActionName("ImportRosters")]
[HttpPost]
public ActionResult PerformImportRosterData(int id, int? actualLength, int? rosterLength)
{
var authenticator = Authenticator(id);
var rosters = authenticator.Api().RosterData().ToDictionary(x => x.Id);
var databaseRosterDatas = SiteDatabase.DeputyRosterData.Where(x => x.SiteID == id)
.ToDictionary(x => x.Id);
Javascript Function:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster, ActualLength, RosterLength }
});
SiteIDRoster = null;
location.reload();
$("#btnRunDeputyNow").modal("hide");
toast.show("Import Successful", 3000);
});
All values are being set but i am getting a 404 error on the url line
POST https://example.org/deputy/PerformImportRosterData 404 ()
I need a way to be able to call this c# method from both html and JS
This can be done if you will modify the URL in your AJAX. It should look something like
url: '<%= Url.Action("YourActionName", "YourControllerName") %>'
or
url: #Url.Action("YourActionName", "YourControllerName")
one more thing, I don't see if you do anything with the result of the call. your script does not have success part
success: function(data) {//do something with the return}
and would be very helpful to have error handler in your call.
full example on how AJAX should look like:
$.ajax({
url: "target.aspx",
type: "GET",
dataType: "html",
success: function (data, status, jqXHR) {
$("#container").html(data);
alert("Local success callback.");
},
error: function (jqXHR, status, err) {
alert("Local error callback.");
},
complete: function (jqXHR, status) {
alert("Local completion callback.");
}
})
For a good tutorial on AJAX read this document
Change after Comment:
my current code is below:
$("#btnDeputyRunNowUpdate").click(function() {
$("#btnRunDeputyNow").modal("hide");
ActualLength = $("#actualRunLength").val();
RosterLength = $("#rosterRunLength").val();
$.ajax({
type: "POST",
url: '<%= Url.Action("PerformImportRosterData", "DeputyController") %>',
data: { SiteIDRoster, ActualLength, RosterLength },
success: function(data) {
console.log(data);
console.log("TESTHERE");
}
});
}
UPDATE:
Noticed one more thing. Your parameters in the controller and AJAX do not match. Please try to replace your a few lines in your AJAX call with:
url: "/deputy/PerformImportRosterData",
data: { id: yourIDValue, actualLength: youractualLengthValue,
rosterLength :yourrosterLengthValue }
remember to set all variable values in javascript , if they have no values set them = to null.
Can you try copy paste code below
$.ajax({
type: "POST",
url: "/deputy/PerformImportRosterData",
data: { SiteIDRoster:999, ActualLength:1, RosterLength:2 }
});
And let me know if it wall cause any errors.
After attempting to solve for a few days, I created a workaround by creating two methods for importing the data. one for the httpPost and the second for import calling from javascript.
Not a great solution but it works. Thanks for your help Yuri

How to pass string value from javascript to function in ASHX

I'm used this code to pass parameter from jQuery to ASHX, actually I want to upload file using Uploadify Plugin and send Parameter named 'Id' to ASHX
function CallHandler() {
$.ajax({
url: "PIU.ashx/MyMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { 'Id': '10000' },
responseType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result) {
alert('Request Failed');
}
and this ASHX code:
public void ProcessRequest(HttpContext context)
{
var employee = Convert.ToInt32(context.Request["Id"]);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string serEmployee = javaScriptSerializer.Serialize(employee);
context.Response.ContentType = "text/html/plain";
context.Response.Write(serEmployee);
parent MyParent = (parent)context.Session["mahdZNUparent"];
//the file data is the file that posted by Uploadify plugin
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string FileName = PostedFile.FileName; // whene i comment this line, the code works
// properly, but when uncomment this line, the code get to 'Request Failed'
}
public bool IsReusable
{
get
{
return false;
}
}
how can I Solve this problem!!!!!!!
You may want to take a loot at this: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And this one too: Using jQuery for AJAX with ASP.NET Webforms

Call ASP.NET C# Controller Method from Javascript

I have a var toto in a javascript file. And I want to call a C# Controller Method who return a string and of course assign the resulted string to toto.
I tried some ways to achieve this but nothing seems to work.
Somebody can explain me the simpliest way to achieve that ? It's a Windows Azure project.
Many Thanks !
You could use AJAX. For example with jQuery you could use the $.getJSON method to send an AJAX request top a controller action that returns a JSON encoded result and inside the success callback use the results:
$.getJSON('/home/someaction', function(result) {
var toto = result.SomeValue;
alert(toto);
});
and the controller action:
public ActionResult SomeAction()
{
return Json(new { SomeValue = "foo bar" }, JsonRequestBehavior.AllowGet);
}
You have to use JSON:
Controler
public class PersonController : Controller
{
[HttpPost]
public JsonResult Create(Person person)
{
return Json(person); //dummy example, just serialize back the received Person object
}
}
Javascript
$.ajax({
type: "POST",
url: "/person/create",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function (result){
console.log(result); //log to the console to see whether it worked
},
error: function (error){
alert("There was an error posting the data to the server: " + error.responseText);
}
});
Read more: http://blog.js-development.com/2011/08/posting-json-data-to-aspnet-mvc-3-web.html#ixzz1wKwNnT34

Jquery ajax post to MVC2 action

I'm using the following script to post to and endpoint, it's hitting the breakpoint on the server so I know the routing is correct.
$(document).ready(function() {
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: JSON.stringify(o),
dataType: 'json',
url: 'home/PingBack',
success: function(result) {
alert(result.success);
}
});
});
The endpoint on the server looks like this.
public JsonResult PingBack(MHolder message)
{
return Json(new { success = "steve"});
}
and the Model looks like this.
public class MHolder
{
public string message { get; set; }
}
I'm sure that in the past the values have been automatically bound to the model, but I can't seem to get anything to be bound atm! Even if I just pass the value as a string, I'm sure it's something silly that I'm missing any ideas?
A few things to notice. You are sending the request as a JSON string (contentType: 'application/json' and JSON.stringify(o)) while on the server you are expecting an object of type MHolder. The default model binder won't do this transformation. You will need to either write a custom model binder capable of deserializing JSON back to an MHolder instance or send the request as key=value pairs (do not stringify):
var o = new Object();
o.message = 'Hi from the page';
$.ajax({
type: 'POST',
data: o,
dataType: 'json',
url: 'home/PingBack',
success: function (result) {
alert(result.success);
}
});
The code seems OK to me, at first glance.
try using...
data : {message : "Hi from the page."},
...to see if this causes the MHolder instance to be populated.
Also, use something like Fiddler to capture your requests and allow you to see exactly what is being posted.

Categories

Resources