I am using jQuery Ajax method with Asp.net MVC 3.0
My jQuery Code is
$.ajax({
type: "POST",
url: "/HomePage/GetAllCategories",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
alert(result);
}
});
And my Action Method is
public JsonResult GetAllCategories()
{
return Json(null, JsonRequestBehavior.AllowGet);
}
I am getting the Error
POST http://localhost:50500/HomePage/GetAllCategories 405 (Method Not
Allowed)
My debugger is not hitting this method.
You have created GET method in the controller and you have set method type as POST in your jquery AJAX call.
$.ajax({
type: "GET",
url: "/HomePage/GetAllCategories",
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
alert(result);
}
});
Just add "/" on the end of the URL:
url: "/HomePage/GetAllCategories/",
Okay, try this. I am using a getJson call to try and fetch the same data.
$.getJSON("/HomePage/GetAllCategories",
function(returnData) {
alert(returnData);
});
Set type GET in the ajax call:
$.ajax({
type: "GET",
url: '#Url.Action("GetAllCategories","HomePage")' ,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
alert(result);
}
});
and action:
[HttpGet]
public JsonResult GetAllCategories()
{
return Json(null, JsonRequestBehavior.AllowGet);
}
If want to do via POST then:
$.ajax({
type: "POST",
url: '#Url.Action("GetAllCategories","HomePage")' ,
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
alert(result);
}
});
and action:
[HttpPost]
public JsonResult GetAllCategories()
{
return Json(null, JsonRequestBehavior.AllowGet);
}
Related
I have my API which accepts Request Param:
#PostMapping(value = "/export")
#ResponseBody
public ResponseEntity<String> bulkExport(
#RequestParam(value = "managedObjects", required = false) List<String> managedObjects) {
//data
}
);
I want to send AJAX POST request.
$.ajax({
type: "POST",
//url: "policy/js_policy",
url: "/export/ ,
async: false,
data: { "managedObjects": ["Audit","Logs"]},
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
//File Handling
}
});
I tried to send managedObjects in URL. In data also I am sending the same.But my API is not working. How to send the #RequestParam from AJAX POST request exactly?
pass a list in Query Param
$.ajax({
...
url: "/export?managedObjects=Audit,Logs" ,
...
});
pass a list in Request Body
$.ajax({
type: "POST",
url: "/export/",
...
data: {managedObjects[0]: "Audit",
managedObjects[1]: "Logs"}
...
});
Try stringifying your data:
var data = {
managedObjects: ["Audit", "Logs"]
}
$.ajax({
type: "POST",
url: "/export/",
async: false,
data: JSON.Stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
}
});
Additionally you should use "name" instead "value" in #RequestParam:
#PostMapping(value = "/export")
#ResponseBody
public ResponseEntity<String> bulkExport(
#RequestParam(name = "managedObjects", required = false) List<String> managedObjects) {
//data
}
);
I think the problem is just with list that you want to send in your request.
var dataToSend = {
list: [{ fieldname: 'ABC' }, { fieldname: 'DEF' }]; // your list should something like this.
$.ajax({
type: "POST",
//url: "policy/js_policy",
url: "/export/?managedObjects=" + Mos ,
async: false,
data: JSON.stringify(dataToSend),
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (XMLHttpRequest, textStatus) {
}
});
I am trying to pass the model from view to controller using ajax AND when I check the value in the JS debugger model has data but it's not binding with controller and the controller model is showing null.
function BulkUpdate()
{
debugger;
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'GET', //GET
data: JSON.stringify({model}),
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
//and my controller code is
public ActionResult BulkUpdate(List<Tag> tags)
{
ModelAccessor obj1 = new ModelAccessor();
obj1.updatedDatas = new List<UpdatedData>();
foreach (var item in tags)
{
var tag = db.Tags.Where(x => x.Id.Equals(item.Id)).FirstOrDefault();
if (tag.TagValue != item.TagValue)
{
UpdatedData changedRow = new UpdatedData {
OldTagValue=tag.TagValue,
NewTagValue=item.TagValue.Trim()
};
obj1.updatedDatas.Add(changedRow);
}
}
return PartialView("_UpdateConfirmationBulk", obj1);
}
I have a solution.
function BulkUpdate()
{
debugger;
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'GET', //GET
data: {'tags':JSON.stringify({model})},
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
Try this because your method expects a parameter named tags and this is missing in you ajax call.
Can you try the type by post?
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'POST', //GET
data: JSON.stringify({model}),
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
I have these method in c# which requires 3 parameters
public void Delete_AgentTools(int ID,int UAM,int mode)
{
some code etc.
}
and I use javascript ajax to call this method and pass the parameter
function Delete_AgentTools(toolAccess, toolId, UAM) {
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: "{'toolAccess':'" + toolAccess + "', 'toolId':'" + toolId + "', 'UAM':'" + UAM + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
}
you see for me I want to simpilfy on how I pass the parameter in javascript. Is it possible to pass it as an object to the c# or simplify the passing of parameters in javascript
You can convert a js object as a JSON using JSON.stringify
var data = {};
data.toolAccess = value1;
data.toolId = value2;
data.UAM = value3;
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
function Delete_AgentTools(toolAccess, toolId, UAM) {
var data = {};
data.mode = toolAccess;
data.ID = toolId;
data.UAM = UAM;
$.ajax({
type: "POST",
url: "IROA_StoredProcedures.asmx/Delete_AgentTools",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function()
{
alert("Tool has been successfully delete");
},
error: function (XMLHttpRequest)
{
alert("error in Delete_AgentTools()");
console.log(XMLHttpRequest);
}
});
No need to change in your C# code.
Why cant I save this, I get 400 (Bad Request),
and on headers response i get The CSRF token could not be verified.
$(document).ready(function() {
$("a#copylink").click(function (e) {
e.preventDefault();
var data = $('#campaign-form').serialize();
$.ajax(
{
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
data: data,
success: function(data){
alert(data);
}
}
)
});
});
on backend:
public function actionCampaignSave()
{
var_dump($_POST);
}
You can pass the [headers] parameter in your ajax call like this.
$.ajax({
url : 'campaignsave',
method : 'POST',,
headers : {
'X-CSRF-TOKEN' : $('input[name="token"]').val()
}
dataType : 'json',
data : data,
success : function(response) {
console.log(response);
}
});
Just make sure you've place {!! csrf_field() !!} on your [view] blade template to append the $(input[name="token"); html tag to get the token value to get the CSRF token as well. Hope this helps
Pass csrf token using headers property on ajax
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
headers: { 'X-CSRF-TOKEN': 'token' }
data: data,
success: function(data){
alert(data);
}
});
Try this it may help you
$.ajax({
type: "POST",
url: 'campaignsave',
data: {test : data},
success: function(data) {
alert(data);
}
});
I am working on a project and have to send a JavaScript Array as a parameter of a ASP.Net function which parameter is ArrayList.
Below is my code,
JavaScript :
var propertyArray = new Array();
propertyArray.push("2");
propertyArray.push("3");
$.ajax({
type: 'POST',
url: 'Default.aspx/SaveTextProperty',
contentType: 'application/json; charset=utf-8',
data: { propertyArray: propertyArray },
dataType: 'json',
success: function (response) {
var result = "Done";
alert(result);
}
});
Default.aspx :
[WebMethod]
public static bool SaveTextProperty(ArrayList propertyArray)
{
//Some code
return true;
}
Here I need to get JavaScript propertyArray as ASP.Net function named SaveTextProperty's parameter.
How can I get it?
Thank you.
You can use as follow
[WebMethod]
public static bool SaveTextProperty(List<string> arr)
{
//Some code
return true;
}
and jquery
var propertyArray = new Array();
propertyArray.push("2");
propertyArray.push("3");
$.ajax({
type: 'POST',
url: 'Default.aspx/SaveTextProperty',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ arr: propertyArray }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: onSuccess,
failure: onError
});
function onSuccess(response) {
alert(response.d);
}
function onError() {
alert("fail");
}