How to send array strings with JS post back to Web Method in ASP.NET, code sample is below:
function service() {
var items = $('#jqxTree').jqxTree('getCheckedItems');
// var jsonText = JSON.stringify({ list: items });
myData = {};
for (index in items) {
myData[index] = items[index].label;
}
$.ajax({
type: "POST",
url: "ServiceConfiguration.aspx/ProcessIndexes",
data: "{'jsonValue': " + JSON.stringify(myData) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
cache: false,
success: function (msg) {
}
});
//alert(items);
}
now i am trying with following:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static void ProcessIndexes(List<string> jsonValue)
{
var serializer = new JavaScriptSerializer();
}
Been awhile since I've been in .NET land, but something like this should work:
$.ajax({
type: "POST",
url: "SomeForm.aspx/SomeWebMethod",
data: JSON.stringify({ someValues: ["foo", "bar"] }),
contentType: "application/json",
dataType: "json",
success: function(resp) {
// handle success here
},
error: function() {
// handle error here
}
});
Related
There is a huge data stored in grid that comes from a sql query joined more than ona table. Data type is Json. I filtered data and then want to sent filtered data to controller. But how it can be?
Here is test json data in javascript block:
var jsonData = {
"FirstName": "John",
"LastName": "Doe",
"DoB": "01/01/1970" };
And this is my javascript function:
function submitForm() {
var user = jsonData;
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(user),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
How to get the Json data in controller? Here is my [HttpPost] method:
[HttpPost]
public IActionResult GetJsonData(String user)
{
//...
return null;
}
user gets null.. Should i change type "String" in method or something else?
Since user is a string, you could try to create an object with a property user:
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
user: JSON.stringify(user)
},
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
Or using FormData:
var formData = new FormData();
formData.append('user', JSON.stringify(user));
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJsonData", "Account")",
contentType: false,
processData: false,
data: formData,
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
I am building a web application where I am calling a ASP.NET WebMethod from jQuery on click of a textbox. The problem is that it returns me the whole ASPX Page. How can I get just the values returned by the Web Method? This is my code:
$("#<%= groupNameTxt.ClientID %>").click(function () {
$.ajax({
url: "../UserGroups.aspx/GetGroupList",
data: "{ }",
// dataType: "json"
type: "POST",
// contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
});
This is my WebMethod from CodeBehind
[System.Web.Services.WebMethod]
public static List<Groups> GetGroupList(string mail)
{
List<Groups> empList = new List<Groups>();
empList.Add(new Groups() { GroupID = 1, GroupName = "Admins" });
empList.Add(new Groups() { GroupID = 2, GroupName = "Employees" });
empList.Add(new Groups() { GroupID = 3, GroupName = "Engineers" });
empList.Add(new Groups() { GroupID = 4, GroupName = "Managers" });
empList.Add(new Groups() { GroupID = 5, GroupName = "Assistants" });
return empList;
}
You need to pass email as parameter as webmethod is expecting a parameter.
$.ajax({
url: "../UserGroups.aspx/GetGroupList",
data: JSON.stringify({ email: "someemail#test.com"}),
dataType: "json"
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
Also specify contentType and dataType
The page was returning since it was not hitting the Web Method. The below code will hit the Web Method correctly. Pass in data as shown below.
$.ajax({
url: "UserGroups.aspx/GetGroupList",
data: '{ mail: "a#a.com"}',
dataType: "json",
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data);
},
error: function (data) {
alert('err');
}
});
I have WCF service method:
[WebInvoke(Method = "POST", UriTemplate = "validateLogin", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)]
[OperationContract]
bool validateLogin(Login objLogin);
I am calling this method through my phonegap code ajax as:
var parameters = {
"EmailID": EmailID,
"Password": Password
};
$.ajax({
url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin",
data: JSON.stringify(parameters),
contentType: "text/xml;charset=utf-8",
dataType: "json",
headers: {
SOAPAction: ''
},
type: 'POST',
processdata: false,
cache: false,
success: function (Data) {
alert("asdsad");
},
error: function (response) {
var value = JSON.stringify(response);
alert("Error in Saving.Please try later."+value);
}
});
But service method is not getting called.
On Network tab it gives me error:
And On Console:
EDIT1:
When i change contenttyp to :appplication/json;charset=utf-8
http://api.jquery.com/jquery.ajax/
crossDomain point in doc
Check it, u send cross domain ajax. It's not allowed by default.
Most probably because of Parameters which you are passing and return type of WCF service. The method should return Object instead of bool. The .Net framework will convert the returned object to the JSON string automatically for you.
Service Side :
[WebInvoke(Method = "POST", UriTemplate = "validateLogin", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)]
[OperationContract]
Object validateLogin(String Email, String Password)
{
//Do your stuff return bool value
}
AJAX Call :
$.ajax({
url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin",
data: function ( {
return JSON.stringify({
Email: "abc#xyz.com",
Password: "XXXXXXXXXX"
});
},
contentType: "text/xml;charset=utf-8",
dataType: "json",
headers: {
SOAPAction: ''
},
type: 'POST',
processdata: false,
cache: false,
success: function (Data) {
alert("asdsad");
},
error: function (response) {
var value = JSON.stringify(response);
alert("Error in Saving.Please try later."+value);
}
});
I'm try using jQuery Ajax for popularize a jqxGrid, but is not success
my jQuery code:
$.ajax(
{
url: "Cliente.aspx/GetClient",
type: "POST",
data: {},
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function(msg) {
alert("error"); //msg is returning error
}
});
I'm try get data with Entity Framework
[WebMethod]
public static string GetClient()
{
string dados;
using (SysContext db = new SysContext())
{
dados = new JavaScriptSerializer().Serialize(db.Clients.ToList());
}
return dados;
}
Where is my error? why
Look over here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
You are missing:
contentType: "application/json; charset=utf-8",
Which is needed to go to the Webmethod. So it will be:
$.ajax(
{
url: "Cliente.aspx/GetClient",
type: "POST",
data: {},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert(msg);
},
error: function(msg) {
alert("error"); //msg is returning error
}
});
I have the following ASP.net web method:
[WebMethod]
public static string SaveUserNew(string id, string[] roles)
{
doStuff(id, roles);
}
I'm calling this code from jQuery Javascript code, but I don't know the syntax for passing an array. Ordinarily, I write jQuery code to call web methods that looks like this:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: '{"foo":"fooValue"}',
contentType: "application/json;",
dataType: "json",
}
Please shed some light on this.
Update: Here is an example of code without arrays that does work:
[WebMethod]
public static string SaveUserNew(string id)
{
return "0";
}
var jdata = '{ "id": "3TWR3"}';
$.ajax({
type: "POST",
url: "UserMgmt.aspx/SaveUserNew",
data: jdata,
contentType: "application/json;",
dataType: "json",
traditional: true
}
});
My intention is to write some code in a similar style where I pass arrays to my web method.
Passing param to webmethod is a little bit tricky. Try this one
[WebMethod]
public static string GetPrompt(string[] name)
{
return "Hello " + name[0] + " and " + name[1];
}
jscript
var param = "{'name':['jack', 'jill']}";
var option = {
error: function(request, status, error) {
alert(error);
},
cache: false,
success: function(data, status) {
alert(data.d);
},
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
url: "../Server/ArrayParam.aspx/GetPrompt"
};
$.ajax(option);
You need to
1) assign the data parameter to have an object with the properties id and roles.
2) assign the roles property an array of strings.
3) Set the traditional setting to true while passing options to ajax call.
e.g:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: {
"id":"1",
"roles":[
"Admin",
"Something",
"Another Thing"
]
},
contentType: "application/json;",
dataType: "json",
traditional: true //#############################
}