Stanislav Muryndin
Stanislav Muryndin

Reputation: 97

get json from controller MVC in java script

I am trying to make some mvc application and I have a problem. I want to get json from mvc controller in javascript file:

JS:

var actionUrl = '@Url.Action("GetJsonTest", "JsonTest")';
$.getJSON(actionUrl, function (response) {
    if (response != null) {
        var html = "<li>" + response.Id + " " + response.Name + " " + response.Author + "</li>";
        $("h2").append(html);
    }
});

Controller:

[HttpGet]
public ActionResult GetJsonTest() {
    var books = new Book() {
        Id = '1',
        Name = "1+1",
        Author = "Varnava",
        Price = 100
    };
    return Json(books, JsonRequestBehavior.AllowGet);
}

It's not working. I have 404 error. It cant get something from controller. What am I doing wrong? Sorry for bad English. Hope you understand what I ask.

Upvotes: 0

Views: 8178

Answers (2)

csharpbd
csharpbd

Reputation: 4066

You have mentioned that you are trying to call GetJsonTest from a javascript file: js. You have used to generate ajax url using

var actionUrl = '@Url.Action("GetJsonTest", "JsonTest")';

above Razor statement from .js file. The problem is that the javascript file can't execute Razor statement. But in .cshtml can. So, if you use this Razor statement from javascript within .cshtml it will work and if you use this Razor statement from javascript within .js it will not work. You have to call like this from .js file:

var actionUrl = '/JsonTest/GetJsonTest';
$.getJSON(actionUrl, function (response) {
    if (response != null) {
        $("h2").append("<li>" + response.Id + " " + response.Name + " " + response.Author + "</li>")
    }
});

Upvotes: 3

gmed
gmed

Reputation: 140

have you defined route in your routeconfig.cs?

you should have something like

   public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
                routes.MapRoute(
                name: "YOUR NAME",
                url: "{YOUR CONTROLLER NAME}/{GetJsonTest}",
                defaults: new { controller = "YOUR CONTROLLER NAME", action = "GetJsonTest" }
            );
    }
    }

Upvotes: 0

Related Questions