我繼承了一些代碼,我試圖找到一個webapi控制器的正確url,但是我對mvc web api的知識缺乏。如何將url.HttpRouteUrl轉換爲普通的字符串url?
我有一個做一個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文件,我想使這個調用。
我需要
我需要幫助找出正確的URL到API控制器,這樣我可以在腳本文件中使用它的幫助。
我試圖
閱讀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){}
我該怎麼做?
// Supply the Action, Controller and any route values that you need
$.post('@Url.Action("EducationPost","EmployeeApi", new { educationName = "educationCreate"})', function(){
// Do something here
});
然而,網址:
但如何將這項工作,一旦我把代碼放在一個js文件?我無法從那裏訪問剃鬚刀的語法。斜線腳本代碼位於可訪問剃鬚刀語法的視圖中。我想將腳本移動到一個js文件並獲取靜態(平面)網址。 – ThunD3eR
正確,這不起作用。通常我推薦使用HTML'data- *'屬性,並使用它來在可能觸發AJAX調用的元素上存儲目標URL。因此,在特定的事件處理程序中,您可以使用'$(this).data('post-url')'來解析請求中的正確URL。那有意義嗎? –
這可能會起作用。我會試一試。請編輯你的答案,如果它的作品,我會接受它。 – ThunD3eR