C# MVC使用Json获取数据并附加到表中
我试图调用一个web API并使用json将数据绑定到一个表。当我在Chrome中运行调试器时,它告诉我它遇到了404错误。当我通过URL调用API时,它工作正常。我认为问题在于我在视图中运行的脚本 这是我的密码 控制器C# MVC使用Json获取数据并附加到表中,c#,json,asp.net-mvc,C#,Json,Asp.net Mvc,我试图调用一个web API并使用json将数据绑定到一个表。当我在Chrome中运行调试器时,它告诉我它遇到了404错误。当我通过URL调用API时,它工作正常。我认为问题在于我在视图中运行的脚本 这是我的密码 控制器 public class WorkspaceController : Controller { // GET: Portal/Workspace public ActionResult Index() { return View(
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);
}
}
使用
Url.Action
helper方法生成aciton方法的正确相对路径。由于您的控制器位于入口
区域内,因此您应该在route value参数中明确指定该区域
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
});
这将生成url,如
/yourSiteName/Portal/Workspace/GetData
,并将其用于getJSON调用。您也可以在此表单中使用
$.getJSON('@Url.Action(Action,Controller)',
function (json) {
...
//TODO : write your code here
有几件事你需要检查,以确保事情设置正确
layout=“~/Areas/Portal/Views/Shared/\u LayoutPage.cshtml”代码>因此,检查是否已经包含jquery文件和其他需要的js文件。如果是,那么您需要在当前视图中删除jquery包含行,因为多次包含它会导致出现问题
Url
类帮助器方法,这也可能会产生问题,因为您可能会在Url中输入一个小错误,这会破坏一些东西。因此,对于包含js和css文件以及ajax调用,可以通过Url
类构建Url,如:
getJson
函数调用,您应该使用Url.Action
方法,该方法将为您生成正确的Url,如下所示:
$.getJSON('@Url.Action("GetData","Workspace")',
您是否在浏览器中检查了控制台是否存在js错误?就是这样。非常感谢。
$.getJSON('@Url.Action(Action,Controller)',
function (json) {
...
//TODO : write your code here
$.getJSON('@Url.Action("GetData","Workspace")',