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.
Related
This is my controller code :
[HttpPost]
public async Task<JsonResult> GetWebsite(int Id)
{
var website = await _uWebsitesService.GetWebsite(Id);
return (website == null ? this.Json("Website Not Found") : this.Json(website));
}
And this is my ajax :
$(".edit-website-btn").on("click", function () {
let id = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "/userpanel/GetWebsite/",
data: { Id: id },
dataType: "json",
contentType: "application/json",
success: function (result) {
console.log(result);
},
error: function (error) {
console.log(error);
},
})
})
When I check the result in console log, it's null when request type is post but when I change The ajax request and controller method to GET it returns the correct object.
this is because for your post method you are using application/json content that doesnt send id to an action, so action is using id=0 by default and can't get any data. Get action has a correct id and returns data. you can try to fix ajax for post by removing contentType: "application/json"
$.ajax({
type: "POST",
url: "/userpanel/GetWebsite/",
data: { Id: id },
dataType: "json",
.....
but imho better to use GET
$.ajax({
type: "GET",
url: "/userpanel/GetWebsite?id="+id,
dataType: "json",
...
and maybe you should try this too
let Id = $(this).data('id');
//or
let Id = this.getAttribute('data-id');
Your data parameter in the ajax call is an object, which just so happens to have a property called Id with the value you want.
However, your C# method expects just an integer, not an object with a property called "Id".
Simply change the JavaScript to only post the integer.
data: id,
To also help out C#'s binding, you should also specify that the parameter is from the request's body. This is techinally optional, but might help with maintainability and ensuring your value doesn't accidently come in from another source (like a rouge query param).
public async Task<JsonResult> GetWebsite([FromBody] int Id)
If you need to pass more than one value in the POST call, you'll need to make a class in C# and bind that instead of the int.
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 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.
I am currently using AJAX to send a JSON object to a Handler written in C#. I was wondering if I can pass the JSON information through a simple url for debugging purposes, just like when I used to use simple parameters (queries) on URLs.
The C# handler deserializes the JSON into a class based on Name and Pass (strings).
So I am trying to go to the handler on the URL like this:
testHandler.ashx?Name=Hey&Pass=Check
Though the C# handler cannot deserialize that properly and the class object is null, if sent that way.
AJAX code of sending a working request to the web server:
var jsonParam = { Name: "test", Pass: "123" }
$.ajax({
url: "Test.ashx",
type: "post", //This sends in url
data: JSON.stringify(jsonParam),
dataType: "json",
contentType: 'application/json; charset=utf-8',
async:false,
success: function (response) {
alert(response.Name);
}
});
So I am wondering what this would look like, if sent through the browser on the URL text box.
P.S - I don't have a problem, I'm just trying to understand the work behind the serialization.
In the sample code you provided you are using JSON object serialized in the body of a POST request. Then you seem to be talking about some testHandler.ashx?Name=Hey&Pass=Check url where you are illustrating the values being passed as query string parameters. There's no longer JSON involved in this case. You should not be passing JSON payloads as parts of the query string. This is a perfectly valid request that you could achieve with the GET verb:
var jsonParam = { Name: "test", Pass: "123" }
$.ajax({
url: "Test.ashx",
type: "GET",
data: jsonParam,
dataType: "json",
success: function (response) {
alert(response.Name);
}
});
In this case you will obviously retrieve the values directly from the query string of course instead of doing any JSON deserialization in your handler:
public void ProcessRequest(HttpContext context)
{
string name = context.Request["Name"];
string pass = context.Request["Pass"];
context.Response.ContentType = "application/json";
...
}
Oh and by the way notice that I have removed the async: false switch from your code coz everytime I see this it makes me vomit.
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
}
});