I'm trying to using FormCollection instead of a model.
I created my AJAX request:
myData = {
id: '1',
name: $("#name").val()
};
$.ajax({
type: "GET",
url: '/testController/Test',
data: JSON.stringify(myData),
contentType: 'application/json; charset=utf-8',
success: function (data) {
// do something
},
error: function (erro) {
console.debug(erro);
}
});
My controller with FormCollection
[HttpGet, ValidateInput(false)]
public JsonResult Test(FormCollection formData)
{
string name = formData["name"].ToString();
}
However, my formData is always null. Does anyone know why?
Thanks
If you are making GET request, you are actually making this request. And you need to access the parameter by Request['id'] & Request['name'].
Request URI: /testController/Test?id={data_id}&name={data_name}
Request Body: <empty>
However, if you are making POST request, you are making this request:
Request URI: /testController/Test
Request Body: {"id":"data_id","name":"data_name"}
The request body is parsed and you can access the data through FormCollection. That's why FormCollection is always null when you make GET request.
Related
Here's a function that calls an ajax get method:
function getSubProjName(projectId) {
console.log(projectId)
var projectName = "";
//ajax get request to get the subproject name
$.ajax({
type: 'GET',
url: '#Url.Action("GetSubProjName", "Home")',
data: { projectId: projectId },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response);
projectName = response;
},
error: function (response) {
console.log(response);
}
});
return projectName;
}
I've checked it a billion times, projectId most definitely receives a value. If it helps, its always a numerical value.
Then I have a method in my controller that SHOULD receive the projectId and do something with it:
[HttpGet]
public JsonResult GetSubProjName([FromBody] string projectId)
{
// some code here
return Json(""); //return the code results back to the view
}
My problem is that I just can't get the controller to actually receive the data from the ajax call. All I get in my string ProjectId, in my controller method, is always null.
Here is any Jquery ajax POST request;
$.ajax({
type: "POST",
url: "/Customers/GetAll",
contentType: "application/json",
dataType: "json",
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
}
});
Here is my Controller Action Method which requested by ajax above;
public IActionResult GetAll()
{
//Method body...
}
How can I get the dataType of any ajax request in base controller or action method?
Try to get accept in headers:
action:
public IActionResult GetAll()
{
string dataType = HttpContext.Request.Headers["accept"].ToString();
//Method body...
}
The headers can be retrieved on the HttpContext object.
if(HttpContext.Request.Headers.TryGetValue("accept", out var acceptHeaders)) {
var firstAcceptHeader = acceptHeaders.FirstOrDefault();
}
You can also access the header value using indexing Headers["accept"], but be aware, that if there is no accept header, for whatever reason, this will throw a NullReferenceException.
I am trying to send a value from jQuery using ajax call and fetch the value in the controller. Below is what I am trying, but the value of A is always null. Can someone help me where I am going wrong.
$.ajax({
type: "POST", //The type of Method being used (GET, SET, POST, etc.)
url: '/Controller1/Index',
contentType: 'application/json; charset=utf-8',
data: { A: "true" }, //Your data to pass to your Controller action
dataType: "json",
success: function (result) {
alert(response.responseText);
alert("Done!");
}
});
C# code
[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost(FilterRule queryBuilder, BootstrapTableQueryType bootstrapTable, string A)
{
string B = A;
}
This is the method from the controller api :
[HttpPost]
public void SaveFloor(int floorID, string json)
{
Floor floor = db.FloorSet.Find(floorID);
floor.SavedJson = json;
floorRepository.Update(floor);
floorRepository.Save();
}
Then I made an ajax call to pass the URL.
function SavingFloor(FloorId, Json) {
$.ajax({
url: "/api/Floor/SaveFloor?FloorID=" + FloorId + "&json=" + Json,
type: "POST",
dataType: 'json',
success: function (data) {
alert('success');
}
});
}
I'm trying to save JSON in database (datatype: nvarchar(MAX)), when I call the URL that executes the saving, I get this error Error HTTP 404.15 - Not Found and it says that the filter module applications is configured to deny a request if the string is too long.
So, what should I do? the JSON that I generate is in fact supposed to be too long, and that's the purpose. Please help.
Send the JSON string as the POST body not as part of the URL. Send it as text and json_decode on the server.
function SavingFloor(FloorId, Json) {
$.ajax({
url: "/api/Floor/SaveFloor?FloorID=" + FloorId,
type: "POST",
data: Json,
dataType: 'text/html',
success: function (data) {
alert('success');
}
});
}
I want to send this POST request by amplifyjs
amplify.request.define('createItem', 'ajax', {
url: baseApiUrl + '/create/?folderid={folderid}',
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8'
});
after that, the execution will be something like this:
createItem = function (callbacks, folderid, itemdata) {
return amplify.request({
resourceId: 'createItem',
data : {
folderid: folderid,
data: itemdata
},
success: callbacks.success,
error: callbacks.error
});
};
"itemData" is already a JSON string. I keep getting the Bad Request status code.
If I change the API URL to:
baseApiUrl + '/create
And after that pass:
return amplify.request({
resourceId: 'createItem',
data :data,
success: callbacks.success,
error: callbacks.error
});
It works just fine, but I need to pass the Id as well. Maybe, I'm missing something here.
You need to combine folderid and itemdata into a single data object. When Amplify reads your data object it will extract the folderid property and place it in the URL of the request. Then it will POST the remaining properties of the data object.