简体   繁体   中英

Calling the controller correctly from JavaScript - ASP.NET MVC

I am using d3js library to draw charts. Here is I'm calling the action like this :

d3.json("CANCEL_REASON/Statistics2", function (data) {
....

My controller is like this :

 public class CANCEL_REASONController : Controller
    {
        private Entities3 db = new Entities3();

        public ActionResult Statistics()
        {
            return View();
        }

        public ActionResult Statistics2()
        {

        ///...
        return Json(data, JsonRequestBehavior.AllowGet);
        }

When I debug the JavaScript, I realize that it's trying to call :

http://localhost:12345/CANCEL_REASON/CANCEL_REASON/Statistics2

When I change js to this :

d3.json("/Statistics2", function (data) {
....

It's trying to call this :

http://localhost:12345/Statistics2

How should I modify my code so that it will call this :

http://localhost:12345/CANCEL_REASON/Statistics2

Thanks.

Use @Url.Action razor helper in order to obtain the correct path.

@Url.Action generates a fully qualified URL to an action method.

d3.json('@Url.Action("Statistics2","CANCEL_REASON")', function (data) {

Or simply

d3.json('/CANCEL_REASON/Statistics2', function (data) {

Add a leading slash and you should be good to go:

d3.json("/CANCEL_REASON/Statistics2", function (data) { ... }

Then your path will relative to the root.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM