I'm trying to join all inputs at an AJAX call to a single string var.
In the backend we have a public JsonResult() which is being called from the frontend with their arguments.
With Request.QueryString.AllKeys we get {string[0]} when it is an AJAX call. When it's a parameter in the URL it returns correctly.
Code we are using is similar to this:
public JsonResult CustomerEdit(Guid customer, int status, string newName, string newLocation, Guid warehouse)
{
...
var parts = new List<string>(); // using System.Collections.Generic
foreach (var key in Request.QueryString.AllKeys)
parts.Add(Request.QueryString[key]);
string result = string.Join(", ", parts);
}
Is there a way to make this work with AJAX call? Or maybe a similar way to achieve this?
UPDATE
AJAX request is similar to:
$.ajax({
url: '/ControllerName/CustomerEdit',
type: "POST",
contentType: "application/json",
data: JSON.stringify({
customer: customer,
status: status,
newName: newName,
newLocation: newLocation,
warehouse: warehouse
}),
success: function (response) {
},
error: function (response) {
}
});
Related
I'm using ajax to send an int64 and a string from a month selector to my server-side, but my variable is always null or 0.
JS:
function deleteConta(id) {
var data = $("#monthSelector").val();
var params = {
id: id,
dataAtual: data
};
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
C#:
public PartialViewResult OnPostDelete([FromBody] long id, string dataAtual)
{
contaDTO.Remove(id, contaDTO.Database, contaDTO.ContaCollection);
dataCorrente = DateTime.ParseExact(dataAtual, "yyyy-MM", null).AddMonths(1);
contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
return Partial("_PartialContas", contas);
}
I already checked with debugger and my variables are ok and filled with value expected (One test was like {id: 50, dataAtual: '2023-01'}
Checked a lot of forums, but Couldn't figure out how to make this thing work.
By declaring the number parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class.
Have you tried to remove it and sending value to the action?
—- UPDATE ——
Try this
function deleteConta(id) {
var data = $("#monthSelector").val();
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
data: { id: id, dataAtual: data },
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
I am calling jquery function on dropdown value change jquery method is ,
function MyFunction() {
alert($('#DDlSurvey').val());
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "GET",
dataType: "json",
success: function (data) {
// loadData(data);
alert(data)
alert("Success");
},
error: function () {
alert("Failed! Please try again.");
}
});
//$('#YourLabelId').val('ReplaceWithThisValue');
}
</script>
Function I'm calling and I am getting dropdown value alert
Now, Function that I am calling is "GetSelectedQuestion" in controller "ConductSurveyController"
Method is like ,
[HttpPost]
public JsonResult GetSelectedQuestion(int prefix)
{
List<SelectList> Questions=new List<SelectList>();
// Here "MyDatabaseEntities " is dbContext, which is created at time of model creation.
SurveyAppEntities ObjectSur = new SurveyAppEntities();
// Questions = ObjectSur.Surveys.Where(a => a.ID.Equals(prefix)).toToList();
I don't think this method is calling as I am getting error
"Failed! Please try again"
From my script.
Hopes for your suggestions
Thanks
var e = from q in ObjectSur.Questions
join b in ObjectSur.SurveyQuestions on q.ID equals b.QuestionID where b.SurveyID.Equals(prefix)
select q ;
return new JsonResult { Data = e, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I think you are using controller name straight forward. your ajax code be something like this.
var PostData= { prefix: $('#DDlSurvey').val() }
var ajaxOptions = {
type: "GET",
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',//Actionname, ControllerName
data: PostData,
dataType: "json",
success: function (result) {
console.log(result);
},
error: function (result) {
}
};
$.ajax(ajaxOptions);
Your method in your controller is decorated with HttpPost, while in your ajax you have specified the type of your request is get . You can either change your method to get like this:
[HttpGet]
public JsonResult GetSelectedQuestion(int prefix)
{
}
Or change your request type to post in your Ajax call:
$.ajax({
url: "#Url.Action("GetSelectedQuestion", "ConductSurveyController")",
data: { prefix: $('#DDlSurvey').val() },
type: "Post",
Also the Controller is redundant in ConductSurveyController, you need to remove it and simply call it as ConductSurvey:
url: '#Url.Action("GetSelectedQuestion", "ConductSurvey")',
My goal is to send a string to and asp.net 5 web api method and then have the method simply return a string as the result.
Here is my js:
$("#btnChangeName").click(function() {
var prodName = $("#txtProductName").val();
var url = 'http://localhost:27081/api/products/changename';
$.ajax({
url: url,
type: 'POST',
dataType: 'text',
data: JSON.stringify({name: prodName}),
success: successFuncApi,
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
Controller:
[HttpPost]
[Route("/api/functions/changename")]
public string ChangeName([FromBody]dynamic value)
{
string newName = ChangeNameHelper(value.name.ToString());
return newName;
}
The strangest thing is that when I use postman or fiddler and send it something like this in the raw body:
{"name":"John"}
it works completely fine. Why doesn't it work with an AJAX request? My dynamic param ends up being null.
Is it 100% a requirement to always bind to a model in the new web api? In this case I am only dealing with a simple string in and a simple string out.
You need to serialize your data using JSON.stringify.
So try replacing this:
data: {name: name}
with this:
data: JSON.stringify({name: name})
JSON is available with modern browsers. But if you need to support IE8, or where your browser does not support it, you need to include json2
UPDATE
#Blake, here's my response to your comment: It is too long to put in the comment section.
I have not used dynamic to receive a complex type into my Web APIs before. However, I have used JToken. Then you can access the name property like this:
public string ChangeName([FromBody]JToken jsonbody)
{
var name = jsonbody.Value<string>("name");
...
}
You do not need to create an object to send the string. This will work.
[HttpPost]
[Route("/api/functions/changename")]
public string ChangeName([FromBody]string value)
{
string newName = ChangeNameHelper(value=);
return newName;
}
The trick is to send a JSON string, not just a string. They are not the same.
$("#btnChangeName").click(function() {
var prodName = $("#txtProductName").val();
var url = 'http://localhost:27081/api/products/changename';
$.ajax({
url: url,
type: 'POST',
dataType: 'text',
contentType:'application/json',
data: JSON.stringify(prodName),
success: successFuncApi,
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
Here is my ajax call
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId/" + id,
type: 'POST',
data: { strIds: strIds },
success: function (data) {
}
});
where id is the integer and strIds is a string contantenation of integers, they look like 123_254_741_6650 ...
And this the server side code ...
[HttpPost]
public IHttpActionResult UpdateResourceContactProductsByResourceContactId
(int id, string strIds)
{
//...
}
When I hit the update button, I'm getting the following error:
{"Message":"No HTTP resource was found that matches the request URI
'http://localhost/api/clients/UpdateResourceContactProductsByResourceContactId/22757'.",
"MessageDetail":"No action was found on the controller 'Clients' that matches the request."}
Am I missing something?
Try this...
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId",
type: 'POST',
data: { id: id, strIds: strIds },
success: function (data) {
}
});
I think you're passing the data wrong. You are passing a object. Either change you method to accept a JObject and use dynamic to pull the strIds out, pass the string by itself, or use it as a URL parameter.
//example using JObject below
[HttpPost]
public IHttpActionResult UpdateResourceContactProductsByResourceContactId(int id, JObject data)//JObject requires Json.NET
{
dynamic json = data;
string ids = json.strIds
}
If you are going to POST an object you need to call JSON.stringify on it too in the javascript.
var data = JSON.stringify({ strIds: strIds });
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId/" + id,
type: 'POST',
data: data,
success: function (data) {
}
});
I want to call a web method in asp.net c# application using the following code
Jquery:
jQuery.ajax({
url: 'AddToCart.aspx/AddTo_Cart',
type: "POST",
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Code:
[System.Web.Services.WebMethod]
public static string AddTo_Cart(int quantity, int itemId)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
But it always call page_load. How can i fix it?
There are quite a few elements of the $.Ajax() that can cause issues if they are not defined correctly. I would suggest rewritting your javascript in its most basic form, you will most likely find that it works fine.
Script example:
$.ajax({
type: "POST",
url: '/Default.aspx/TestMethod',
data: '{message: "HAI" }',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
},
failure: function (response) {
alert(response.d);
}
});
WebMethod example:
[WebMethod]
public static string TestMethod(string message)
{
return "The message" + message;
}
This is a bit late, but I just stumbled on this problem, trying to resolve my own problem of this kind. I then realized that I had this line in the ajax post wrong:
data: "{'quantity' : " + total_qty + ",'itemId':" + itemId + "}",
It should be:
data: "{quantity : '" + total_qty + "',itemId: '" + itemId + "'}",
As well as the WebMethod to:
public static string AddTo_Cart(string quantity, string itemId)
And this resolved my problem.
Hope it may be of help to someone else as well.
Necro'ing this Question ;)
You need to change the data being sent as Stringified JSON, that way you can modularize the Ajax call into a single supportable function.
First Step: Extract data construction
/***
* This helper is used to call WebMethods from the page WebMethods.aspx
*
* #method - String value; the name of the Web Method to execute
* #data - JSON Object; the JSON structure data to pass, it will be Stringified
* before sending
* #beforeSend - Function(xhr, sett)
* #success - Function(data, status, xhr)
* #error - Function(xhr, status, err)
*/
function AddToCartAjax(method, data, beforeSend, success, error) {
$.ajax({
url: 'AddToCart.aspx/', + method,
data: JSON.stringify(data),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: beforeSend,
success: success,
error: error
})
}
Second Step: Generalize WebMethod
[WebMethod]
public static string AddTo_Cart ( object items ) {
var js = new JavaScriptSerializer();
var json = js.ConvertToType<Dictionary<string , int>>( items );
SpiritsShared.ShoppingCart.AddItem(json["itemId"], json["quantity"]);
return "Add";
}
Third Step: Call it where you need it
This can be called just about anywhere, JS-file, HTML-file, or Server-side construction.
var items = { "quantity": total_qty, "itemId": itemId };
AddToCartAjax("AddTo_Cart", items,
function (xhr, sett) { // #beforeSend
alert("Start!!!");
}, function (data, status, xhr) { // #success
alert("a");
}, function(xhr, status, err){ // #error
alert("Sorry!!!");
});
One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :
[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
//parse parameters here
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Add";
}
Edit : or Pass int parameters from ajax call.
I'm not sure why that isn't working, It works fine on my test. But here is an alternative technique that might help.
Instead of calling the method in the AJAX url, just use the page .aspx url, and add the method as a parameter in the data object. Then when it calls page_load, your data will be in the Request.Form variable.
jQuery
jQuery.ajax({
url: 'AddToCart.aspx',
type: "POST",
data: {
method: 'AddTo_Cart', quantity: total_qty, itemId: itemId
},
dataType: "json",
beforeSend: function () {
alert("Start!!! ");
},
success: function (data) {
alert("a");
},
failure: function (msg) { alert("Sorry!!! "); }
});
C# Page Load:
if (!Page.IsPostBack)
{
if (Request.Form["method"] == "AddTo_Cart")
{
int q, id;
int.TryParse(Request.Form["quantity"], out q);
int.TryParse(Request.Form["itemId"], out id);
AddTo_Cart(q,id);
}
}
The problem is at [System.Web.Services.WebMethod], add [WebMethod(EnableSession = false)] and you could get rid of page life cycle, by default EnableSession is true in Page and making page to come in life though life cycle events..
Please refer below page for more details
http://msdn.microsoft.com/en-us/library/system.web.configuration.pagessection.enablesessionstate.aspx
you need to JSON.stringify the data parameter before sending it.
Here is your answer.
use
jquery.json-2.2.min.js
and
jquery-1.8.3.min.js
Javascript :
function CallAddToCart(eitemId, equantity) {
var itemId = Number(eitemId);
var quantity = equantity;
var dataValue = "{itemId:'" + itemId+ "', quantity :'"+ quantity "'}" ;
$.ajax({
url: "AddToCart.aspx/AddTo_Cart",
type: "POST",
dataType: "json",
data: dataValue,
contentType: "application/json; charset=utf-8",
success: function (msg) {
alert("Success");
},
error: function () { alert(arguments[2]); }
});
}
and your C# web method should be
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string AddTo_Cart(int itemId, string quantity)
{
SpiritsShared.ShoppingCart.AddItem(itemId, quantity);
return "Item Added Successfully";
}
From any of the button click or any other html control event you can call to the javascript method with the parameter which in turn calls to the webmethod to get the value in json format.