2
votes

I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.

FYI, I am using MVC 5 and Umbraco 7.

I currently have the ajax code within the partial view (will want to move this to a js file at some point).

Here is the ajax code:

function GetTime(name) {
    var result = "";

    $.ajax({
        url: '/TimeDifference/GetTimeDifference',
        //url: '@Url.Action("GetTimeDifference", "TimeDifference")',
        type: 'GET',
        //data: JSON.stringify({ location: name }),
        data: ({ location: name }),
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        async: false,
        cache: false,
        success: function (msg) {
            result = msg;
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert(xhr.status);
      }
    });

    return result;
}

Here is the Controller:

public class TimeDifferenceController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
      [HttpGet]
       public JsonResult GetTimeDifference(string location)
        {
            DateTime utc = DateTime.UtcNow;
            string timeZoneName = GetTimeZoneName(location);
            TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
            TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);

            TimeSpan utcOffset = gmt.GetUtcOffset(utc);
            TimeSpan localOffset = local.GetUtcOffset(utc);
            TimeSpan difference = localOffset - utcOffset;

            return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);

           }
}

The above code gives me a 404 Not Found Error:

Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100

If I use: url: '@Url.Action("GetTimeDifference", "TimeDifference")'

The @Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.

I have also tried:

@Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url:  $("#URLName").val()

Url is still Null.

I have added entries in to the Global.asax.cs for routing i.e.

routes.MapRoute(
                 "Default", // Route name
                 "{controller}/{action}/{id}", // URL with parameters
                 new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
             );

This doesn't seem to do anything.

I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.

As I am new to this I'm sure it something very simple I am missing.

Many thanks, HH

1
I recommend reading up on the UmbracoApiController. It maps routes automatically for you and helps give you access to useful things like the UmbracoHelper. If you struggle with getting it working, please say so and I'll post an answer showing how it works.harvzor
@Harvey - thank you for you reply you were spot on with the UmbracoAPIcontroller.hungryhorse

1 Answers

2
votes

Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.

Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.