MVC使用Json获取数据并附加到表

时间:2017-10-23 18:43:52

标签: c# json asp.net-mvc

我正在尝试调用Web API并使用json将数据绑定到表。当我在Chrome中运行调试器时,它告诉我它出现了404错误。当我通过URL调用API时它工作正常。我认为问题是我在视图中运行的脚本。

这是我的代码

控制器

    public class WorkspaceController : Controller
{
    // GET: Portal/Workspace
    public ActionResult Index()
    {
        return View();
    }

    [HttpGet]
    public JsonResult GetData()
    {
        var contactId = 3311;

        List<WorkItemActiveGridModel> collection = new List<WorkItemActiveGridModel>();

        HttpClient httpClient = new HttpClient { BaseAddress = new Uri(string.Format("{0}://{1}", Request.Url.Scheme, WebConfigurationManager.AppSettings[ConfigurationKeys.DataServicesUri])) };
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        HttpResponseMessage httpResponseMessage = httpClient.GetAsync("Api/WorkItem/Active/" + contactId).Result;
        if (httpResponseMessage.IsSuccessStatusCode)
        {
            collection = JsonConvert.DeserializeObject<List<WorkItemActiveGridModel>>(httpResponseMessage.Content.ReadAsStringAsync().GetAwaiter().GetResult());
        }

        return Json(collection, JsonRequestBehavior.AllowGet);

    }
}

}

查看

@model dynamic
@{
ViewBag.Title = "Customer Portal";
Layout = "~/Areas/Portal/Views/Shared/_LayoutPage.cshtml";
}


<div class="callout callout-danger">
    <h4>Open Items</h4>
    <table class="table table-bordered table-responsive table-hover table-striped">
        <tr>
            <th>WorkItemID </th>
            <th>Title </th>
            <th>State </th>
            <th>PercentComplete </th>
            <th>OwnerName </th>
            <th>ContactName </th>
            <th>ReleaseDtm </th>
        </tr>
    </table>
</div>
</section>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>  
<script>
$(document).ready(function () {
    $.getJSON("Workspace/GetData",
            function (json) {
                var tr;
                for (var i = 0; i < json.length; i++) {
                    tr = $('<tr/>');
                    tr.append("<td>" + json[i].workItemId + "</td>");
                    tr.append("<td>" + json[i].title + "</td>");
                    tr.append("<td>" + json[i].state + "</td>");
                    tr.append("<td>" + json[i].percentComplete + "</td>");
                    tr.append("<td>" + json[i].owner + "</td>");
                    tr.append("<td>" + json[i].contact + "</td>");
                    tr.append("<td>" + json[i].releaseDate + "</td>");
                    $('table').append(tr);
                }
            });  
});

通过调用URL返回的API数据:

[
 {
"typeIcon": "fa-weixin",
"priorityIcon": null,
"attachmentIcon": "False",
"workItemId": 1,
"type": "(1) Critical",
"title": "[RELEASE READY]Test 1",
"state": "New",
"priority": "(3) Medium",
"score": 1,
"percentComplete": 0,
"contact": "User 1",
"account": "Department",
"owner": "Tech 1",
"created": "2017-08-25T22:41:47.623",
"dueDate": "2017-08-25T22:41:47.623",
"releaseDate": "2017-08-25T22:41:47.623"
},
{
"typeIcon": "fa-weixin",
"priorityIcon": "fa-exclamation-circle",
"attachmentIcon": "False",
"workItemId": 6,
"type": "(3) Medium",
"title": "[RELEASE READY]Test 3",
"state": "Approved",
"priority": "(1) Critical",
"score": 3,
"percentComplete": 20,
"contact": "User 1",
"account": "Department",
"owner": "Tech 1 ",
"created": "2017-08-25T22:41:50.827",
"dueDate": "2017-08-25T22:41:50.827",
"releaseDate": "2017-08-25T22:41:47.623"
}
]

3 个答案:

答案 0 :(得分:1)

您也可以使用此表格

  $.getJSON('@Url.Action(Action,Controller)',
            function (json) {
    ...
    //TODO : write your code here

答案 1 :(得分:0)

使用Url.Action辅助方法生成aciton方法的正确相对路径。由于您的控制器位于Portal区域内,因此您应该在路由值参数

中明确指定
 var url ="@Url.Action("GetData","Workspace",new { area= "Portal"})";
 $.getJSON(url,function(json){
     console.log(json);
     alert("Received response from ajax call");
     //to do : continue processing the response json array
 });

这会生成类似/yourSiteName/Portal/Workspace/GetData的网址,并将其用于getJSON调用。

答案 2 :(得分:0)

您需要检查一些事项以确保正确设置。

  1. 您已在视图String queryString = RequestContext.getCurrentContext().getRequest().getQueryString(); 的顶部定义了主布局,因此请检查是否已包含jquery文件和其他所需的js文件。如果是,那么您需要在当前视图中删除jquery包含行,因为多次包含它会让您遇到问题。
  2. 您正在使用所有相对路径而不使用Layout = "~/Areas/Portal/Views/Shared/_LayoutPage.cshtml";类助手方法,这也可能会产生问题,因为您可能会在网址中输入一个小错误,这会破坏事情。因此,为了包含js和css文件以及对于ajax调用,可以通过Url类构建url,如:

     
  3. 对于Url函数调用,您应该使用getJson方法来处理为您生成正确的网址:

    Url.Action