【发布时间】:2016-05-18 14:32:20
【问题描述】:
我继承了一些代码,我正在尝试找出 webapi 控制器的正确 url,但是我缺乏 mvc web api 的知识。
我有一个内联脚本,它正在制作这样的 ajax 帖子:
$('#saveNewEducation').on('click', function () {
var educationAdd = {
'educationId': $('#newEducation').val(),
'startDate': $('#newEducationDate').val(),
'identificationId': $('#identificationId').val(),
'educationNote': $('#newEducationNote').val(),
'examinerId': $('#newExaminer').val()
};
$.post('@Url.HttpRouteUrl("DefaultApi", new { controller = "EmployeeApi", educationName = "educationCreate" })', educationAdd)
.done(function (data, textStatus, jqXhr) {
if (jqXhr.status == 200) {
$('#save-education').modal('show');
} else {
$('#fail-save-employee').modal('show');
}
})
.fail(function (jqXhr) {
var education = $("#new-education");
if (jqXhr.status == 409) {
$('#future-save-employee').modal('show');
} else {
if (jqXhr.status == 400) {
clearErrors(education);
var validationErrors = $.parseJSON(jqXhr.responseText);
$.each(validationErrors.ModelState, function (i, ival) {
remoteErrors(education, i, ival);
});
} else {
$('fail-save-employee').modal('show');
}
}
});
我不喜欢内联脚本,我创建了一个单独的 js 文件,我想从中进行调用。
我需要帮助
我需要帮助找出 api 控制器的正确 url,以便我可以在脚本文件中使用它。
我试过了
阅读this article我尝试了以下:
$.post('/DefaultApi/EmployeeApi', educationAdd)
这给了我一个
404 未找到错误。
在内联脚本中,url 是这样的:
$.post('@Url.HttpRouteUrl("DefaultApi", new { controller = "EmployeeApi", educationName = "educationCreate" })', educationAdd)
WebApiConfig.cs 文件:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
我试图在 EmployeeApi 控制器中访问的方法:
public IHttpActionResult EducationPost(EmployeeEducation model, string educationName){}
我该怎么做?
【问题讨论】:
标签: c# jquery asp.net-web-api asp.net-mvc-5