【问题标题】:Accessing Web API in MVC 5 using jQuery使用 jQuery 在 MVC 5 中访问 Web API
【发布时间】:2014-09-21 15:07:28
【问题描述】:

我正在创建一个 MVC 5 应用程序。我添加了 ADO.Net 实体数据模型并使用实体框架创建了 Web API 2 控制器。我还创建了 DTO 类。以下是我的 DTO 课程:

public class CollegeDetailsController : ApiController
{
    private CollegeDbContext db = new CollegeDbContext();

    // GET: api/CollegeDetails
    public IQueryable<CollegeDTO> GetCollegeDetails()
    {
        var colleges = from c in db.CollegeDetails
                       select new CollegeDTO()
                       {
                           Name= c.CollegeName,
                           ContactPersonName= c.ContactPerson,
                           CollegeState= c.State,
                           CollegeCity=c.City
                       };
        return colleges;
    }

我正在使用 jQuery 访问它:

    function GetAllColleges() {
    $(document).ready(function () {
        jQuery.support.cors = true;
        $.ajax({
            url: "http://localhost:57071/api/collegedetails",
            type: "Get",
            dataType: 'json',
            success: function (data) { WriteCollegeData(data); },
            error: function (msg) { alert(msg); }
        });
    });
}

function WriteCollegeData(colleges) {
    var result = "<table><th>College Name</th><th>Contact Person</th><th>College State</th><th>Contact City</th>";
    $.each(colleges, function (index, item) {
        result += "<tr><td>" + item.Name + "</td><td>" + item.ContactPersonName + "</td><td>" + item.CollegeState + "</td><td>" + item.CollegeCity + "</td></tr>";
    });
    result += "</table>";
    $("#CollegeData").html(result);
}

我的 Cshthml 页面:

@{
    ViewBag.Title = "College";
}

@section scripts{
    @Scripts.Render("~/bundles/App");
}

<h2>College Details</h2>

<div class="row">
    <div class="panel panel-default">
        <div class="panel-heading">
            <h2 class="panel-title">Colleges</h2>
        </div>
        <div class="panel-body" id= "CollegeData">

        </div>
    </div>
    <div class="col-md-4">

    </div>
    <div class="col-md-4">

    </div>
</div>

访问此页面时,数据未绑定到面板,控制台没有错误。

【问题讨论】:

    标签: jquery asp.net-web-api asp.net-mvc-5


    【解决方案1】:

    我解决了。我刚刚删除了function GetAllColleges() {}。现在价值观来了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-29
      • 2014-09-15
      • 2015-02-20
      • 1970-01-01
      相关资源
      最近更新 更多