0

I have an MVC View called Index, and I want to return the data from a Car object. I am using jQuery AJAX to call the data from an API Controller

Using postman I am able to get data back, but when debugging the view completely skips the ajax get call. I am not sure why I have json serialization as well as cors enabled in my apiconfig file so that shouldn't be an issue.

Any suggestions are much appreciated

MVC View:

   @{
    ViewBag.Title = "Home Page";
}

<!DocType HTML>
<html>
<head>
    <style>
        .dvdItem {
            height: 180px;
            width: 70%;
            border: 1px solid lightgray;
            background-color: lightgray;
            margin-top: 20px;
            margin-left: 35px;
            -webkit-box-shadow: -1px 2px 18px 0px rgba(0, 0, 0, 0.64);
            -moz-box-shadow: -1px 2px 18px 0px rgba(0, 0, 0, 0.64);
            box-shadow: -1px 2px 18px 0px rgba(0, 0, 0, 0.64);
            padding: 10px;
        }

    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <div class="jumbotron well">
                    <h2>
                        Hello, world!
                    </h2>
                    <p>
                        This is a template for a simple marketing or informational website. It includes a large callout called the hero unit and three supporting pieces of content. Use it as a starting point to create something more unique.
                    </p>
                    <p>
                        <a class="btn btn-primary btn-large" href="#">Learn more</a>
                    </p>
                </div>
                <div id="item-details" class="col-md-9"></div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
    <script src="home.js"></script>
    <script type="text/javascript">
    $(document).ready(function () {

        loadItems();
    });


    function loadItems() {

        $.ajax({
            type: 'GET',
            url: '/Car/Featured',
            success: function (itemArray) {

                $.each(itemArray, function (index, Car) {
                    $('#item-details').append('<a onclick="GetItemId(' + Car.ReleaseYear + ')"><div id="item" class="dvdItem col-md-3"><p>' + Car.Model + '</p><p>' + Car.Make + '</p><p>$' + Car.Price.toFixed([2]) + '</p></div></a>');
                });
            },
            error: function () {
                $('#errorMessages')
                    .append($('<li>')
                        .attr({ class: 'List-group-item list-group-item-danger' })
                        .text('Error'));
            }
        });

    </script>
</body>

</html>

The API Controller with the actions:

    using GuildCars.DAL;
using GuildCars.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Results;

namespace GuildCars.Controllers
{
    public class CarController : ApiController
    {
        CarRepository carRepository = new CarRepository();


        [AllowAnonymous]
        [Route("car/featured")]
        [AcceptVerbs("GET")]
        public IHttpActionResult Featured()
        {
            List<Car> found =  carRepository.GetFeatured();
            if (found == null)
            {
                return NotFound();
            }
            return Ok(found);
        }

    }
}
2
  • Are the missing quotes in url: '/Car/Featured' a typo? Commented Oct 31, 2017 at 11:28
  • 1
    You have no function called loadItems(). JavaScript is case-sensitive. Also, url: /Car/Featured is a syntax error. Look at your browser's debugging console when debugging client-side code. Commented Oct 31, 2017 at 11:30

1 Answer 1

1

You will not able to call the api function as url: '/Car/Featured' because it already handled by WebApiConfig. You need to call the function as

  url: 'api/Car/Featured'

The default Registration is usually found in WebApiConfig and tends to look like this

public static class WebApiConfig
{
  public static void Register(HttpConfiguration config)
  {
    // Attribute routing.
    config.MapHttpAttributeRoutes();

    // Convention-based routing.
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
  }
}

You need to edit the routeTemplate in the convention-based setup.

public static class WebApiConfig
{
 public static void Register(HttpConfiguration config)
 {
    // Attribute routing.
    config.MapHttpAttributeRoutes();

    // Convention-based routing.
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
  }
}

Then you can use url as :

'Car/Featured'
Sign up to request clarification or add additional context in comments.

Comments

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.