I have a webMethod with a single argument I am trying to call via jQuery Ajax. Now the argument is supposed to be the query string of the url in which I am making the ajax call. I don't know how to pass the query string as an argument into the method from the jQuery ajax. My Code is as follows
C# Method
[WebMethod]
public static string FollowUser(string userId)
{
//Code to follow user
//returns a string value
}
jQuery Ajax
$(document).ready(function() {
$("#btnFollow").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/FollowUser",
data: //how do I pass the query string here
contentType: "application/json; charset=utf-8", datatype: "json",
context: this,
success: function(msg) {
//I'm doing some stuff here
}
},
error: function(response) {
alert(response.d);
}
});
});
});
Someone help me out. Thanks.
You need to pass the data as part of the the URL or change the method to GET. When submitting an aJax post with data you are sending the data as part of the request body (form data). This won't be as a query string attribute but part of the content. Instead change the URL To include the data. Example.
Default.aspx/FollowUser?userId=user1
changing to a GET method will force the post parameters to be part of the query string instead.
Related
I remember I read it somewhere that when submitting parameters values via ajax to API, there is an option so they don't show up in the URL. I've tried put them into data like:
$.ajax({
type: "GET",
url: "/api/myController/myLunch",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {"tableID":111, "firstCourse": "soup", ... }, // show up in header but not working
header: {"tableID":111, "firstCourse": "soup", ... }, // neither
success: function (data) { ... }
});
Controller get method:
[HttpGet]
[Route("myLunch")]
public IHttpActionResult myLunch(int tableID, string firstCourse, ...)
{ ... }
I kept getting 404 back. Basically I don't want to see like this:
/api/myController/myLunch?tableID=111&firstCourse=soup
I want to see only
/api/myController/myLunch
You can hide parameters from the URL using the POST method. Actually, the main difference between the GET and POST methods is GET shows parameters in the URL while POST hides parameters from the URL. Meanwhile, you can use both to post data.
You can hide parameter from Url using request method POST. Meanwhile if you use GET method it will show params as query params in url.
I'm using $.ajax({...}); to send some data to my server (the aspx's CodeBehind file in c#). In order to receive this data to work with in the CodeBehind file, I have to use a static WebMethod ([System.Web.Services.WebMethod]). Once I work with this data, I want to either redirect them to a new page if there was a success (In my case, a successful credit card charge), otherwise, send an alert to the user that something went wrong (i.e., credit card charge randomly didn't work).
Is there a way to access/alter the current page's markup via this static WebMethod (e.g., add <script>alert("Something went wrong")</script>), without the ability to use asp page controls? (i.e., this which is the page in non-static methods in CodeBehind files)
You may need to use Success and Failure section of $.ajax syntax. Please refer an example below. I hope your web method returns string to make this work.
Sample WebMeethod
[ScriptMethod()]
[WebMethod]
public static string YourWebMethod()
{
String yourMessageString = String.Empty;
//process as per your logic
yourMessageString = "Some Message";
return yourMessageString;
}
$.ajax({
type: "POST",
url: "/yourpage.aspx/yourwebmethod",
async: false,
contentType: "application/json; charset=utf-8",
data: "your data",
dataType: "json",
success: function (message) {
alert(message);
},
error: function () {
alert("error");
},
failure: function () {
alert('failure');
}
});
I'm tring to pass a value I pull from a data-attribute in my markup to a C# method using jQuery Ajax. In this example, the value for QuestionNumber results in a 1. EMHQQuestion is an enum with values 1 through 15. I expect my C# method DeleteCondition to receive that 1 but instead I get a 500 internal server error: "Invalid web service call, missing value for parameter: 'questionNumber'.
Any suggestions?
function DeleteConditions() {
var QuestionNumber = $('.noRadioButton').data('questionnumber');
$.ajax({
url: "mhqpreinterview.aspx/deletecondition",
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
questionNumber: QuestionNumber
});
Dialog.dialog('close');
}
..
[WebMethod(EnableSession = true)]
public static void DeleteCondition(EMHQQuestion questionNumber)
{
//stuff
}
I struggled with this EXACT same thing when making AJAX reqs to web form methods.
For your c# method:
[System.Web.Services.WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string DeleteCondition(EMHQQuestion questionNumber)
{
// do enum stuff here
}
Please note that I have changed the method type from void to string. It is a good idea to send some identifiable information back to the client. Even if you do not have to send data back, it gives you a chance to customize success or helpful debugging information.
Here are the changes you have to make to your AJAX object:
var params = '{ questionNumber: ' + JSON.stringify(QuestionNumber) + '}';
var post = {
type: 'POST',
url: 'mhqpreinterview.aspx/deletecondition',
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json"
};
$.ajax(post);
What you should be taking away from the above javascript, is the use of JSON.stringify before you send to your method. You have to make sure QuestionNumber is parameterized correctly and already valid JSON for the web service method to receive.
If you find its still not working, check to see what value is being stored inside QuestionNumber before you are trying to send it.
The above code does work with me, any other troubles post a comment and I will do my best to help answer it.
Use data jquery ajax field:
data: JSON.stringify({QuestionNumber: QuestionNumber}),
dataType: "json",
I'm using ASP.NET MVC3 with Jquery. I'm trying to pass my form elements back to the controller using something like this (Please note I removed success and error code for simplicity):
var formElements = $("#myForm").serialize();
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: {collection: formElements},
success:
error:
dataType: "json"
});
My question is what should the parameter in my controller method look like:
Here is my controller method:
public ActionResult SubmitChanges(WHAT GOES HERE?)
{
}
So what I'm really looking for is what should be the type of the parameter going into the controller method? I want to be able to retrieve the values of the form elements in the controller.
So here is what I did. I have about 20-30 elements on my form so I really didn't want to have to turn each one into a parameter or list them all out in the collection.
In the jquery, I did the following:
var formElements = $("#myForm").serialize();
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: { parms: formElements },
success:
error:
dataType: "json"
});
It then goes into my controller as a string:
public ActionResult SubmitChanges(string parms)
I then found a function to parse that string (seems to be working)
NameValueCollection qscoll = HttpUtility.ParseQueryString(parms);
This seems to work without listing out all of the form elements.
Assuming your form elements all correspond to your model (let's say it's MyModel), then it should simply be:
public ActionResult SubmitChanges(MyModel model)
{
}
MVC default model binding will do the rest :).
Make sure you change your data definition in the jQuery ajax method though, you've already serialized it. Just do:
data: formElements,
I'm assuming the following in your jQuery ajax method is a copy and paste error?
success:
error:
If it's not, then make sure you either remove it, or change them to:
success: function (result) {
//do something
},
error: function () {
//do something on error
}
The problem is that their is no model that corresponds to my form
elements.
Then you can have this:
public ActionResult SubmitChanges(int id, string name)
{
}
And then pass in the individual items:
var o = {
id = $("#id_elem_id").val(),
name = $("#name_elem_id").val()
}
$.ajax({
type: "POST",
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: JSON.stringify(o),
success:
error:
dataType: "json"
});
where id_elem_id and name_elem_id are the ids of your html elements. And add any additional parameters you need, just follow along.
You were almost there. Just get rid of the brackets around your data parameter:
var formElements = $('#myForm').serialize();
$.ajax({
type: 'POST',
url: ScriptResolveUrl("~/Report/SubmitChanges"),
data: formElements,
success: function(result) {
// handle the success of the AJAX request
},
error: function() {
// an error occurred
}
});
I have a user control that I'm creating that is using some AJAX in jQuery.
I need to call a function in the code-behind of my control, but every example I find online looks like this:
$("input").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetResult",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//do something
}
});
});
This works fine if I have the method in the Default.aspx page. But I don't want to have the function there, I need the function in the code-behind of my control. How can I modify the url property to call the correct function?
I tried:
url: "GetResult"
but that didn't work.
The way to handle this is to have the webmethod in your page, then just pass the values directly to a control method with the same signature in your control - there is no other way to do this.
In other words, ALL the page method does is call the usercontrol method so it is really small. IF you have the same signature for multiple child controls, you could pass a parameter to tell the page method which one to call/use.
EDIT: Per request (very very simple example). You can find other examples with more complex types being passed to the server side method. for instance see my answer here: Jquery .ajax async postback on C# UserControl
Example:
Page method: note the "static" part.
[WebMethod]
public static string GetServerTimeString()
{
return MyNamespace.UserControls.Menu.ucHelloWorld();
}
User Control Method:
public static string ucHelloWorld()
{
return "howdy from myUserControl.cs at: " + DateTime.Now.ToString();
}
Client ajax via jquery:
$(document).ready(function()
{
/***************************************/
function testLoadTime(jdata)
{
$("#timeResult").text(jdata);
};
$("#testTimeServerButton").click(function()
{
//alert("beep");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data)
{
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
url: "MyPage.aspx/GetServerTimeString",
success: function(msg)
{
testLoadTime(msg);
}
});
});
});
Note: the dataFilter: function(data)... part of the ajax is so that it works with 2.0 and 3.5 asp.net ajax without changing the client code.
You can't...WebMethods have to be in WebServices or Pages, they cannot be inside UserControls.
Think about it a different way to see the issue a bit clearer...what's the URL to a UserControl? Since there's no way to access them you can't get at the method directly. You could try another way perhaps, maybe a proxy method in your page?