Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}
Related
I want to send data from javascript to c# controller using ajax, but when the Add method in my controller is called all its arguments are null
AJAX:
function addRequest(name, price, about){
$.ajax({
url: 'Services/Add',
type: 'POST',
contentType: "application/json; charset=utf-8",
data: {
'name' : name ,
'price' : price,
'about' : about,
},
dataType: "json",
success: (insert) => {
if (insert) {
$('#result').fadeIn(200).html(insert).fadeOut(200, () => {
location.reload()
})
}
}
})
}
My controller:
[ApiController]
[Route("[controller]")]
public class ServicesController: Controller
{
[HttpPost]
[Route("Add")]
public async Task Add(string? name, string? price, string? about)
{
await Context.Services.AddAsync(new Service
{
Name = name,
Price = price,
About = about
});
await Context.SaveChangesAsync();
}
}
I think binding of this controller in not working, you are sending object by ajax but you are expecting three separte primitives
try:
[HttpPost]
[Route("Add")]
public async Task Add(Service service)
{
await Context.Services.AddAsync(service);
}
or try adding setup binding attributes
try this
[HttpPost]
[Route("Add")]
public async Task Add(Service model) {
//
}
Try using a service class to receive the JSON rather using distinct values.
Follow below links to learn more.
https://www.aspsnippets.com/Articles/Pass-Send-Model-object-in-jQuery-ajax-POST-request-to-Controller-method-in-ASPNet-MVC.aspx
https://www.c-sharpcorner.com/article/asp-net-mvc-how-to-use-ajax-with-parameters/
I get better results using the $.post() method of the jquery library
here is an example:
$.post(`Services/Add/?name=${name}&price=${price}&about=${about}`,
function (insert) {
if (insert) {
$('#result').fadeIn(200).html(insert).fadeOut(200, () => {
location. Reload()
})
}
});
Source: JQuery Documentation about $.post()
Check if your controller is authorized or not. If you want the controller to work without any authorization then you have to add allowannoymous attribute on your controller since no access token is given in the ajax call.
I am new to ASP and I am trying to take a string in my JS code and post it to my controller so that I can use it to query my database.
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (response) {
alert(userCounty);
},
error: function (response) {
alert("failed");
}
});
}
Controller
[HttpPost]
public ActionResult Index (string userCounty)
{
var query = //use linq to query database
return View(query);
}
I only ever get the "success" alert when I use a JsonResult function in my Controller but I need it to eventually return a LINQ query to the View(); function and that hasn't worked when using a JsonResult function. Any ideas would be helpful. I don't necessarily have to use ajax if there is a better way. I just need a way to pass the string stored in userCounty to my controller.
Please change your controller method like this
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
var query = //use linq to query database
return View(query);
}
For viewing the page, you'll need
[HttpGet]
public ActionResult Index()
{
return View();
}
I have a controller (InformationTechnologyController). That controller contains an action (LocationChangeRequest). That action takes an optional parameter(id).
public ActionResult LocationChangeRequest(ChangeRequestType id = ChangeRequestType.WithinDepartment)
That action returns a view with the current model data.
return View(locationChangeRequest);
Within that view, there's a function that performs an ajax post (code below) to search for employee information.
Employee Search 1
The url to reach that view is:
http:// [not relavant here] /InformationTechnology/LocationChangeRequest
When a user attempts to reach that view using a route parameter, the Employee Search function does not perform.
The url to reach the view with the routing parameter is:
http:// [not relavant here] /InformationTechnology/LocationChangeRequest/1
What I discovered is the HttpPost method in the InformationTechnology controller is not being hit when using the /1 parameter in the path. Athough it seems to have to do with the parameter in the path, I can't seem to figure out how to solve the problem.
Any advice on how to handle hitting the HttpPost through the url with the parameter would be appreciated.
The HttpPost code is as follows:
[HttpPost]
public JsonResult SearchUser(string term)
{
...
return Json(results, JsonRequestBehavior.AllowGet);
}
The javascript code is as follows:
$.ajax({
url: searchUserUrl,
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data,
function (item) {
return { label: item.Name, value: item.HexKey }; }));
},
error: function (xhr, error) {
console.debug(xhr); console.debug(error);}
})
You need to define a global variable for using the $ as below.
var $=jQuery.noConflict();
I'm trying to use ajax with post method but it keep poping me this error
An attempt was made to call the method \u0027SendEmail\u0027 using a GET request, which is not allowed
Here is the js
var obj = { name: name, company: company, country: country, email: email, msg: Msg }
var json = JSON.stringify(obj);
$.ajax({
method: "POST",
url: "ContactUs.aspx/SendEmail",
contentType: "application/json; charset=UTF-8",
data: json,
dataType:"json",
success: function (data) {
var a = 3;
},
error:function(a,b){
var a = 43;
}
})
and here is the server side on c#
[WebMethod]
public static void SendEmail(string name, string company, string country, string email, string msg)
{
}
Thanks in advance!
You should follow this way:
Your backend method which you already decorated with [WebMethod] and added a reference of using System.Web.Services;, I've changed the method to return something so it can be verified whether it works or not.
[WebMethod]
public static String sendEmail(string param)
{
return "Your String";
}
within your .aspx page, add scriptManager for enabling client side calling to your code behind methods
<asp:ScriptManager ID="scriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
Finally within your JQuery script, call the method like this:
$(document).ready(function () {
PageMethods.sendEmail("", onSuccess);
function onSuccess(response)
{
alert(response);
}});
Hope it helps!
Try to use [HttpPost] instead of [WebMethod] and remove static.
Is it a REST API or MVC?
Folks
I have a problem with consuming a rest using javascript.
This Rest is already being used in other applications, where PHP and Aspx conserve the same described below.
#Controller
#RequestMapping("/userlogin")
public class UserRest {
#Autowired
private UserService userService;
#RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseStatus(HttpStatus.OK)
public ResponseEntity<RetornUser> login(#RequestBody User user) {
RetornUser retornUser = new RetornUser();
try {
user = userService.autenticarUsuario(user);
retornUser.setUsuario(usuario);
retornUser.setCodigoRetorno(1);
} catch (Exception e) {
retornUser.setCodigoRetorno(-1);
retornUser.setMensagem(e.getMessage());
}
return new ResponseEntity<>(retornUser, HttpStatus.OK);
}
}
The code above works perfectly with PHP, Aspx and Java calls.
When I call the routine, the JS is falling into the error function before receiving the return.
The worst thing is that the JS error is not bringing the reason. Below the code in pure HTML.
function logar() {
try {
var json = JSON.stringify(usuario);
json = "{\"nome\": \"garra\",\"senha\": \"1234\"}";
$.ajax({
type: "POST",
url: "http://localhost:8080/garrasystem/webservice/userlogin/login",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 300000, // sets timeout to 3 seconds
success: function (retorno) {
alert(retorno);
},
error: function (data, textStatus, xhr) {
alert(data.responseText);
}
});
} catch (e) {
console.log(e);
}
}
The way it is there, when I send debug, it calls the normal login method, but it falls into the error function, nor does it expect the login method to perform the return.
I put the method return String only and nothing too.
My Spring is 4.
I'm waiting for some help
Vinicius Castro
Looks like you are passing string instead of json object. Could you try passing the following:
var data = {
nome: "garra",
senha: "1234"
};
Folks
Being focused on a single problem, I forgot to analyze the button type. It was like type submit, so it was not working. It is like experiencing these kind of mistakes.
Thank you to all who supported me