I've been at this for hours now and still not got it right... someone please put me out of my misery!
javascript:
var calcParams = {}
calcParams.calcName="gwp_mat";
calcParams.components=124.332;
//return manager.impactCalc(calcName, componentArray)
return postData("{calcParams2:" + JSON.stringify(calcParams) + "}")
.then(querySucceeded)
.fail(queryFailed);
function postData(cp) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/api/breeze/testCalc",
data: cp,
success: function (data) {
alert(data);
return data;
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
}
});
}
model:
Public Class calcParams2
Public calcName As String
Public calcNumber As Double
End Class
Server code:
<System.Web.Services.WebMethod()> _
Public Function testCalc(cp As calcParams2) As Double
Dim c As New calcs
Return cp.calcNumber
End Function
If I debug it, the "cp" parameter in the javascript postData function is:
"{calcParams2:{"calcName":"gwp_mat","components":124.332}}"
and yet in my web method, calcname is "nothing" and components is "0.0"
If I don't use JSON.Stringify I get a null object in my web method. I think I had one version of code where the calcName was passed but the components value was still zero. That was when I just called "return postData(JSON.stringify(calcParams))" I think.
You only need to send the object parameters in the JSON:
return postData(JSON.stringify(calcParams)) ...
However your JQuery Object needs to have the same parameter names as your Server object. Change your server object to be:
Public Class calcParams2
Public calcName As String
Public components As Double
End Class
OR change your client object:
var calcParams = {}
calcParams.calcName="gwp_mat";
calcParams.calcNumber=124.332;
Related
In my web service (order.asmx) I have a method which accept a viewmodel as a parameter. Method signature is below.
public string CreateOrder(OrderModel order)
and my order.cs is like below,
public class OrderModel: BaseClass
{
public OrderModel()
{
this.RestaurantIDs = new List<long>();
}
public long OrderID { get; set; }
public List<long> RestaurantIDs { get; set; }
}
I'm passing all the order related details using ajax call to this service method. To pass the RestaurantIDs I'm using an array which gives me 500 server error. I tried with stringify as well but didnt work. Anyone can help me with this?
ajax call
function createOrderObject()
{
var order = new object;
order.CustomerName = $("#txtName").val();
order.RestaurantIDs = selectedRestaurants.map(function (obj) {
return obj.RestaurantID;
});
}
// here the selectedRestaurants is object array.
function createOrder()
{
var order = createOrderObject();
var url = '/Service/OrderService.asmx/CreateOrder';
var dataSet = '{orderModel:' + JSON.stringify(order) + '}';
var orderInfo = $.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: url,
data: dataSet,
dataType: "json",
error: function () {
giveNotification({ NotificationCode: 500, Message: "Internal Server Error, Please try again." });
loadingImg(ele, "hide");
});
}
the error message }
I want to send array of objects from ajax call to controller action.
On back-end side I have
container classes:
public class MyContainer
{
public string Id { get; set; }
public Filter[] Filters { get; set; }
}
public class Filter
{
public string Name { get; set; }
public string[] Values { get; set; }
}
and action:
public ActionResult MyAction(MyContainer container)
{
var id = container.Id;
foreach(Filter filter in container.Filters)
{
//Do something
}
}
On front-end side I have
$(document).on('click', 'mySelector', function (event) {
//Create first object
var firstIds = {};
firstIds.Name = "Custom Name 1";
firstIds.Values = GetIds('param1'); //this return an array of strings
//Create second object
var secondIds = {};
secondIds.Name = "Custome Name 2";
secondIds.Values = GetIds('param2'); //another array
var Id = $(this).attr('id'); //id of element
//Add objects to array
var filters = [];
filters.push(firstIds);
filters.push(secondIds);
$.ajax({
method: "GET",
url: baseUrl+"/MyAction",
//traditional: true, //I tried with and without that parameter
data:
{
Id: Id,
Filters: filters
},
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
});
So if I use it like in example on top, container-object in action have Id value and have array of 2 elements in Filters, however both of them have Name and Values as null.
With traditional set to True, I got container.Id set but container.Filters = null.
Any suggestion?
Thank you.
Use a POST request in combination with JSON.stringify() method.
C#
[HttpPost]
public ActionResult MyAction(MyContainer container)
{
var id = container.Id;
foreach(Filter filter in container.Filters)
{
//Do something
}
}
JQUERY
$.ajax({
method: "POST",
url: baseUrl+"/MyAction",
data:JSON.stringify(
{
Id: Id,
Filters: filters
}),
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
Why do you need JSON.stringify() method ?
contentType is the type of data you're sending, so application/json; The default is application/x-www-form-urlencoded; charset=UTF-8.
If you use application/json, you have to use JSON.stringify() in order to send JSON object.
JSON.stringify() turns a javascript object to json text and stores it in a string.
You should use POST method instead of GET in ajax request. As you are posting data. and also your action should have [HttpPost] decorator.
$.ajax({
method: "POST",
url: baseUrl+"/MyAction",
data:
{
Id: Id,
Filters: filters
},
contentType: 'application/json',
success: function (res) {
alert('success')
}
});
Though its an old post, adding my bit to it. I would ask if you are returning a view from the action or not? here it seems like you are not returning a view but just wanting to update some data.
But in case you wanted to return a view, for e.g like showing some product info, then you would just pass the selected product's id to the action method, retrieve the related product information and then pass on this data as a model to the view, and then return the complete view. In this case you don't need a separate ajax call to process the data, instead just do it when you are requesting for the view itself (through the action method).
On the contrary if you already have the view rendered and are just wanting to change the data inside the current view then just resort to an ajax call to get the data without any view.
Hope it helps
Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}
I'm trying to set up what should be a very simple call from an MVC page to a controller using JavaScript. This is my Controller:
Imports System.Web.Mvc
Namespace Controllers
Public Class DataController
Inherits Controller
Function Index() As ActionResult
Return View()
End Function
<HttpPost>
Function SaveData(payload As String) As String
If payload IsNot Nothing AndAlso payload.Length > 0 Then
Return "Good"
Else
Return "Bad"
End If
End Function
End Class
End Namespace
this is my View (Index.vbhtml):
#Code
ViewData("Title") = "Index"
End Code
<h2>Index</h2>
#Code
Html.BeginForm()
#:Save Data
Html.EndForm()
End Code
and this is my JavaScript (included via the _layout.vbhtml file):
function SaveData() {
var payload = "TEST_DATA_GOES_HERE";
// Calls controller correctly but data is null
$.ajax({
url: "/Data/SaveData",
type: "POST",
processData: false,
dataType: String,
data: { payload: payload }
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
// Returns a 500 error
$.post("/Data/SaveData", { Payload: payload }, function (data) { alert('Application saved. ' + data); }, "String");
// Calls controller correctly but data is null
$.post("/Data/SaveData", payload, function () { alert('Application saved.' + data); }, "String");
}
Everything connects up nicely when debugging but the payload variable arrives as Nothing in the SaveData function. I've tried using $.post but with similar problems and all the references I've found to using either method simply assume that it will work first time without error and don't have any troubleshooting tips.
How do you configure the $.ajax or $.post functions to correctly call a controller and pass a simple string?
You need to set processData to true as you are sending an object which will need to be converted to a querystring.
From the API:
ProcessData
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
http://api.jquery.com/jQuery.ajax/
Thanks to the answer form Rory this is what I ended up with:
Controller:
<HttpPost>
Function SaveData(payload As String) As Boolean
If payload IsNot Nothing AndAlso payload.Length > 0 Then
Return True
Else
Return False
End If
End Function
JavaScript:
function SaveData() {
var payload = "TEST_DATA_GOES_HERE";
// Calls controller correctly but data is null
$.ajax({
url: "/Data/SaveData/",
type: "POST",
data: { payload: payload }
})
.done(function () { alert('Application saved.'); })
.fail(function () { alert('Application failed to save.'); });
}
Note that the $.ajax call doesn't have the processData or dataType elements and that the name of the variable matches the case of the parameter.
However what I found out is that my real problem was actually caused by passing XML as a string in this call. The XML cannot be simply passed as is in the query string. If you do that it arrives as null most likely because the MVC model binder can't process the resulting bad querystring.
my problem is following.
I try to parse some data via ajax, passing the data to my controller:
AJAX
$.ajax({
type: "GET",
url: "ParseOrganizaitonPath",
data: {
organizationPath: $('#organizationPath').val()
},
success:
function (data) {
//data is from type string with value "System.string[]"
//but should be from type System.string[]
});
}
});
Controller
public string[] ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
return organizations.ToArray();
}
I am reaching the controller method and in it everything is fine, but the data that is comming back (ajax part, success method) is just a string ("System.string[]", data[0] S, data[1]y data[2]s...) but not the data I want. (For example if i pass the input "test/one" I want to have as result data[0] test, data[1] one)
Hope you understand what my Problem is.
Thanks in advance!
Julian
Have to tried to use the JavaScriptSerializer? Have a look at this example:
public string ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
return oSerializer.Serialize(organizations);
}
To deserialize the JSON string with JavaScript you can use the parse function:
var array = JSON.parse(data);
I found a way where you don't have to serialize it (on c# site) and parse it (on javascript site)
Just use the JSON Method that is inherited from the Controller and return an JsonResult:
public JsonResult ParseOrganizaitonPath(string organizationPath)
{
List<string> organizations = organizationPath.Split('/').ToList();
return JSON(organizations);
}
On the client site (javascript) you have to use JSON.stringfy(dataObject) for data that you want to send to your controller-method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "ParseOrganizaitonPath",
data: JSON.stringify(myDataObject),
success:
function (data) {
//use your data
});
}
});
That's how it worked for me.
Good luck!
Julian