1

I have two controller, C1 and C2.
C2 has a method named M2 which is returning a JsonResult.

Now i am calling method M2 from view V1 using $.ajax call but I guess that the relative path to C2/M2 is not working fine.

$.ajax({
         type: "GET",
         url: "/C2/M2",
         success: function (data) {
             alert(data);
         }
});

Notice:
View V1 is rendered using controller C1

What is wrong with this call ?

public class C1 : Controller
{
    public ActionResult Package(object Id)
    {
        return View("PackageO");
    }
}

public class C2: Controller
{
    public JsonResult SelectAll()
    {
        return Json(_rep.SelectAll(), JsonRequestBehavior.AllowGet);
    }
}

Under ready() of jQuery in View 'PackageO' i am using IIFE

$(function () {
      var resultant = "";
      $.ajax({
           type: "GET",
           url: "./C2/SelectAll",
           //url: "@Url.Action('SelectAll', 'C2')",
           done: function (data) {
                alert("success");
           },
           fail: function (ex) {
                alert("fail");
           }
      });
});

1 Answer 1

2

You should never hard-code URLs in MVC.

Instead use @Url.Action.

url: '@Url.Action("FunctionName", "ControllerName")',

If this doesn't fix your problem tell us what kind of error(s) are you getting.

Also, for the sake of your sanity, use the fail method.

$.ajax("http://url")
    .done(function() {
    alert("success");
})
    .fail(function() {
    alert("error");
})

One last note, success is deprecated as of jQuery 1.8; you should use done instead.

Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for your reply.i am getting following error<br/>"NetworkError: 500 Internal Server Error - localhost:20097/Package/Package/…"
Is that URL correct? If it is then the problem is in that controller. Unless you are forgetting to send some required parameters...
i am self invoking this function under ready() of jquery as i want to populate dropdownlist
Does your project run OK? Can you navigate manually to C2's SelectAll?
I suggested you to use Url.Action and you have failed at copy pasting my code and changing the strings.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.