使用jQuery AJAX在MVC中返回数据以调用APIController

时间:2017-10-31 11:26:27

标签: jquery asp.net ajax asp.net-mvc api

我有一个名为Index的MVC视图,我想从Car对象返回数据。 我正在使用jQuery AJAX从API控制器调用数据

使用postman我可以恢复数据,但是在调试视图时完全跳过ajax get调用。我不知道为什么我的apiconfig文件中启用了json序列化以及启用了cors,因此不应该成为问题。

非常感谢任何建议

MVC查看:

   @{
    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>

具有操作的API控制器:

    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);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

您将无法将api函数称为url:'/ Car / Featured',因为它已由WebApiConfig处理。您需要将该函数调用为

compile "com.google.android.gms:play-services-auth:$firebaseVersion"

默认注册通常在WebApiConfig中找到,并且往往看起来像这样

  url: 'api/Car/Featured'

您需要在基于约定的设置中编辑routeTemplate。

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 }
    );
  }
}

然后你可以使用url:

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 }
    );
  }
}