コントローラー アクションにカテゴリを追加すると、JSON オブジェクトが返されます。
return Json(new { categoryName = category.Name, isPrimary = isPrim ? "1" : "-1", categoryId = categoryId }, JsonRequestBehavior.AllowGet);
JS ハンドラー関数で、ページに項目を追加します。
...
var totalLink = "<li style='color: #bbbbbb;'>" + result.categoryName + "<a class='removeCategoryButton' href='#lnk#'>remove</a></li>";
var lnk = '@Url.Action("RemoveCategoryFromLocation", "Location", new{locationId = Model.Location.TicketId, categoryId=-1})';
totalLink = totalLink.replace('#lnk#', lnk);
totalLink = totalLink.replace('-1', result.categoryId);
$('#otherCategories').append(totalLink);
...
リンクの削除をクリックすると、次の関数が呼び出されます。
$(function () {
$('.removeCategoryButton').click(function (event) {
event.preventDefault();
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
if(result.categoryName == 1) {
$(this).closest('li').remove();
}
}
});
return false;
});
});
しかし、次のエラーが表示されます。
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
このエラーは、アイテムを追加してページに追加した直後に削除したい場合にのみ発生します。ページを更新してリンクの削除をクリックすると、問題なく動作します。
上記のカテゴリからエラーが発生したときに注意してください削除されたので、呼び出しは何らかの理由でこのエラーをポップするだけで機能します。