ASP.NET MVC - JQuery call from url without action not working - c#

I have a http://localhost:54393/CreateTest/4fwp36 which working fine but when I call http://localhost:54393/CreateTest/RemoveControlsNew from jQuery ajax then it is not working giving an error also not calling into a controller if any one can help me out as I am stuck here more then 1 day
I have tried this but it's not working:
MVC JQuery call from url without action
This is my route config:
routes.MapRoute(
name: "CreateTest",
url: "CreateTest/{id}",
defaults: new { controller = "CreateTest", action = "Index", id = UrlParameter.Optional }
);
Above code works perfectly when I call from another controller calling it like this:
return Redirect("/CreateTest/"+ strTestID);
When I try to call on same controller with ajax post method
RemoveControls: function (rid) {
var MyAppUrlSettings = {
MyUsefulUrl: "/CreateTest/RemoveControlsNew"
}
$.ajax({
type: 'POST',
dataType: "JSON",
async: false,
//url: '#Url.Action("RemoveControlsNew",Request.Url.Scheme)',
url: MyAppUrlSettings.MyUsefulUrl,
contentType: 'application/json; charset=utf-8',
data: {
rid: rid,
bgcolor: CREATETEST.globalbgcolor,
fontcolor: CREATETEST.globalfontcolor,
fontsize: CREATETEST.globalfontsize
},
success:
function (response) {
var data = response;
if (data == 'Error') {
CREATETEST.showerror('Some thing went wrong you cannot remove a question at the moment for selected option');
}
else {
$("#AddControlNew").load(location.href + " #AddControlNew");
}
},
error:
function (response) {
console.log(response);
CREATETEST.showerror("Error: " + response);
}
});
},
Then these is not working and my method is not called.
I am getting this error:
Error on page
Controller code for Ajax call
Regular Controller code

Your "Error on Page" image doesn't show anything useful, are you getting a 404, 202, 405 Header Status Code
Please post code, not images.
Apply the [FromBody] attribute to a parameter to populate its properties from the body of an HTTP request. The ASP.NET Core runtime delegates the responsibility of reading the body to an input formatter.
public JsonResult RemoveControlsNew([FromBody] int rid, string bgcolor, string fontcolor, string fontsize)

Related

Ajax call to MVC controllers

I'm trying to pass some data with ajax call to a c# mvc controller. Even though the task should be straight forward, I am unable to get the mvc controller to read the data I'm passing through the ajax call....
I've implemented the following code within my MVC controller
[HttpPost]
public string tt(string o)
{
return o;
}
[HttpPost]
public string tt2(string o)
{
return "lala";
}
And I'm triggering the following ajax calls from the browser
$.ajax({
url: "/Home/tt2",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
$.ajax({
url: "/Home/tt",
type: "POST",
contentType: "application/json;",
data: JSON.stringify({ o: 'asdas'}),
success: function(e){console.log(e+' correct');},
error: function(e){console.log(e+' incorrect');}
});
As a result when running the first ajax call the result is
lala correct
And for the second ajax call, the result is
undefined correct
In the mean time these are some stuff I tried
Adding dataType: "json", to the ajax call
Changing the string data from {o: 'asdas'} to 'asdas'
Removing the JSON.stringify
Adding the charset=utf-8 to the contentType
Changing the ajax call type and MVC controller method from POST to GET to PUT
Changing the MVC controller method parameter from string to int
Removing the error method from the ajax call
Changing the data from data: {o: 'asdas'} to data: {"o":"asdas"}
Changing the data from data: {"o":"asdas"} to data: JSON.stringify({"o":"asdas"})
I know that simple string or int can be passed through the URL as query strings but it would be an issue when passing a list of objects..
Something aside is that the call is being done correctly to the URL because when I set a breakpoint within the called method, it does get triggered but the parameter always is null..
Any thoughts on how to make ajax call work?
try:
[HttpPost]
public string tt([FromBody]string o)
{
return o;
}
Your request should be like this:
$.ajax({
url: '#Url.Action("tt", "Home")',
data: {
"o": "asdasdas"
},
cache: false,
type: "POST",
success: function (response) {
},
error: function (xhr) {
}
});

ajax request to razor page using handler

I am trying to get data from Active.cshtml.cs file using ajax call.
Here is the jquery code:
var turl = '/Active?handler=Clients/' + id;
$.ajax({
type: "GET",
url: turl,
dataType: "json",
success: function (result) {
alert(JSON.stringify(result));
});
Here is Active.cshtml.cs method
public JsonResult OnGetClients()
{
return new JsonResult("new result");
}
The status is 200 Ok, but it shows the entire webpage in response. Ideally it should return "new result" in Network tab of developer tools. Is it that I have Active.cshtml and Active.cshtml.cs in Pages that creates the confusion? How can I resolve it?
Thanks
For razor pages, you should be passing the parameter value(s) for your handler method in querystring.
This should work.
yourSiteBaseUrl/Index?handler=Clients&53
Assuming your OnGetClients has an id parameter.
public JsonResult OnGetClients(int id)
{
return new JsonResult("new result:"+id);
}
So your ajax code should look something like this
var id = 53;
var turl = '/Index?handler=Clients&id=' + id;
$.ajax({
type: "GET",
url: turl,
success: function (result) {
console.log(result);
}
});

Pass int to webapi

I know this has been asked a thousand times. But I can't find my error. I narrowed it down by testing it without a parameter, which worked and then tried various things. Like, get or post, [FromBody] or not. etc.
Perhaps I should just show my code or I should stop for today and just celebrate that it is almost weekend.
[HttpGet] // also tried post instead of get
public HttpResponseMessage Get(int id)
{
return Request.CreateResponse(HttpStatusCode.OK); // breakpoint set, not hit
}
My Js code:
var myObj = {};
myObj["id"] = parseInt(id);
var json = JSON.stringify(myObj);
alert(json); // display: { id = 2134 }, seems fine to me
$.ajax({
type: "GET", // also tried post
dataType: "json",
url: '/api/CheckPossible/Get',
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
I have received a lot of bad requests (400) and I did got it to work without a parameter. So it is not a routing issue.
edit
$.ajax({
type: "GET",
dataType: "json",
url: '/api/CheckPossible/Get/?id=1234', // also tried Get?id=1234
contentType: "application/json; charset=utf-8",
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
Did not work. Perhaps I am missing something else too
You can't pass a http message body to a GET method, you have to pass parameters either in the URL or in the header. For a web api you should pass them in the URL and you can do this as a query string or as part of the URL.
To get it to work with the query string change the url to
url: '/api/CheckPossible/?id=' + myObj["id"],
leave out the data as this won't do anything with get.
If you want to make the parameter a part of the URL then change your route to include it. I prefer the Route attribute for flexible routing, you can also change the global routing scheme.
[HttpGet] // also tried post instead of get
[Route("api/CheckPossible/{id:int}"]
public HttpResponseMessage Get(int id)
{
}
and change your url to
url: '/api/CheckPossible/' + myObj["id"]

AJAX Call not hitting Controller Method - ASP.NET MVC

I've tries setting breakpoints at the Controller method. But it does not stop there. The alerts "clicked" and the next one work perfectly fine. But the controller method is not called. Any help is appreciated. Here's my ajax call and my controller method.
var Url = "#Url.Action("~/Home/Get_Location")";
$("#gotoloc").click(function() {
alert("clicked");
alert(lat +" "+ lon);
$.ajax({
type: "POST",
url: Url,
data: {
latitude: lat,
longitude: lon
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Hello:" + response)
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
alert("ignored");
});
public JsonResult Get_Location(double latitude,double longitude)
{
string loc = latitude + "/" + longitude;
return Json(loc, JsonRequestBehavior.AllowGet);
}
You are using the Url.Action method incorrectly.
Try this
var Url = "#Url.Action("Get_Location","Home")";
The above overload takes the action method name as first parameter and controller names as second parameter
Also, i see you are passing incorrect contentType request header. contentType headers tells the server what is the type of data the client is sending. Your current code says you are sending json data. But you have 2 parameters in your action method and the json serializer will fail to properly map the posted data to it, hence you will be getting a 500 response from the server.
This should work, assuming there are no other js errors in your page
var url = "#Url.Action("Get_Location","Home")";
$.ajax({
type: "POST",
url: url,
data: { latitude: 44, longitude: 55 },
success: function (response) {
console.log("Hello:" + response);
},
failure: function (response) {
console.log(response.responseText);
},
error: function (response) {
console.log(response.responseText);
}
});

ajax jquery .net results in "The resource cannot be found."

I'm trying to do a simple ajax call in .net
Any advice?
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
I call the webmethod in my browser like this:
http://localhost.com/Ajax/WebService1.asmx/HelloWorld
Which results in
"The resource cannot be found."
Probably because of the url syntax.
My routes are setup like:
routes.IgnoreRoute("Ajax/");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
If I delete the MapRoute, the webcall works, but the rest of my website fails.
Any advice?
Update:
I changed to use a controller. When I call it with a url in my browser I hit my breakpoint in the controller. But not when I run this code:
<div id="Result">
Kig her!
</div>
#section javascript {
$(function () {
$("#FirstReminder").datepicker();
$("#EndDate").datepicker();
});
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#Result").click(function() {
alert('kkk');
$.ajax({
type: "POST",
url: "AjaxWorkflow/GetSteps",
data: {workflowId: "1", workflowStep: "test"},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
}
});
});
});
Update 2:
I solved it by changing the line to
data: "{workflowId: '1', workflowStep: 'test'}",
Because you are using routing, I assume this is an MVC website? If so you should use an ActionResult in your controller instead of a WebMethod. Try this:
public string HelloWorld()
{
return Content("Hello World");
}
You would then call this using jQuery on the following URL: http://localhost.com/[Controller]/HelloWorld
Note, in the example here I am returning a string - as per your original example. It is also possible to return an object via JSON, using return Json(obj);
WebMethods belong to ASP.NET WebForms while the routing belongs to ASP.NET MVC. You'd better not mix the two technologies.
In this case most of the application seems to be ASP.NET MVC if after removing the routing everything stops working. That means that you want to replace the WebMethod with a Controller Action.

Categories