cafej
cafej

Reputation: 95

How to call a cs function in another library with ajax

Im working with the model view/Controller, so im trying to keep files in different folders like this enter image description here

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

Upvotes: 1

Views: 1138

Answers (3)

scniro
scniro

Reputation: 16989

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

Upvotes: 0

Ganesh
Ganesh

Reputation: 62

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

Upvotes: 0

C. Helling
C. Helling

Reputation: 1402

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).

Upvotes: 2

Related Questions