I'm getting a 404 when issuing an ajax call - c#

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) {
}
});

Related

C# and Ajax - Posting 2 values from JS to C#

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);
}
});
}

Request.QueryString with AJAX request

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) {
}
});

why POST request method returns null but GET request returns correct object

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.

Trying to Get Data using Ajax call to Controller method MVC My code Attached

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")',

getting data from controller in error function of jquery ajax -- Asp.net MVC

I have a jquery ajax script like following
$.ajax({
type: "POST",
url: "Main/receive", // the method we are calling
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ 'p':$("#txtname").val() }),
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
// Or if you are returning something
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
And I am calling to Controller action method. The data is sending to the controller's action method and I am also receiving data from the controller. But the data that I am receiving is inside the error function of jquery ajax.
I want it to be inside the success function.
Why my success function is not getting called.
Following is my controller's action method,
[HttpPost]
public string receive(string p)
{
ViewBag.name = p;
return p;
}
The reason for the error is that you have specified that the returned data type be json (in the line dataType: "json",) but you method returns text. You have 2 options.
Change the controller method to return json using return Json(p);
Change the ajax option to dataType: "text", or just omit it
However you can improve your script as noted below
$.ajax({
type: "POST",
url: '#Url.Action("receive", "Main")', // don't hardcode url's
data: { p: $("#txtname").val() }, // no need to stringify (delete the contentType: option)
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no zzzz:('+result.responseText);
}
});
or even simpler
$.post('#Url.Action("receive", "Main")', { p: $("#txtname").val() }, function(result) {
alert('Yay! It worked!');
}).fail(function(result) {
alert('Oh no zzzz:('+result.responseText);
});
Notes: You should always use #Url.Action() to generate the correct urls, and it is not necessary in this case to stringify the data (but you need to remove the contentType: line so it used the default application/x-www-form-urlencoded; charset=UTF-8)
In addition, this is not strictly a POST (your not changing data on the server - but I assume this is just for testing). And there is no point in the line ViewBag.name = p; - it does nothing in your context, and as soon as you return from the method, ViewBag is lost anyway.
try to change your controller code as follows
[HttpPost]
public ActionResult List(string p)
{
ViewBag.name = p;
return Json(ViewBag);
}
Your controller method should look like this:
[HttpPost]
public ActionResult receive(string p)
{
return Json(p);
}

Categories

Resources