javascriptasp.net-corejson.netasp.net-core-3.0jsonresult

This JS code works properly in the .cshtml file, but not working in .js file(external javascript file)


This JS code works properly in the .cshtml file, but not working in .js file(external javascript file). Can anyone help me? i am also trying with Ajax GET but also not working in js file

[Area("Administrator")]
[Authorize(Roles = "Administrator")]
public class HomeController : Controller
{
    private readonly ApplicationDbContext _context;

    public HomeController(ApplicationDbContext context)
    {
        _context = context;
    }

    public JsonResult EarningChart()
    {
        var earning = _context.Orders.Where(o => o.Status == OrderStatus.Completed).ToList();
        return Json (earning);
    }

 <script type="text/javascript">
$(function () {
    //ajax function for fetch data
    $.ajax({
        type: "GET",
        url: '@Url.Action("EarningChart","Home",new { area ="Administrator"})',
        success: function (data) {
            alert('succeed');
        },
        error: function () {
            alert('Failed');
        }
    });
});
    </script>


Solution

  • @Url.Action() is razor (server side) code and can't be used in .js file .You can add a hidden field in your main page to store url, then use javascript/jquery to get the url from the hidden field in .js file :

    @Html.Hidden("MyURL", Url.Action("EarningChart","Home",,new { area ="Administrator"}))
    

    Then in your js file :

    <script type="text/javascript">
        $(function () {
    
            var myUrl = $("#MyURL").val();
            //ajax function for fetch data
            $.ajax({
                type: "GET",
                url: myUrl,
                success: function (data) {
                    alert('succeed');
                },
                error: function () {
                    alert('Failed');
                }
            });
        });
    </script>