Ajax and jQuery queries will not work if JavaScript is disabled on the client. The best way to do this work is to use the URL from the <a>
href tag as follows:
<a href="@Url.Action("UpdateCategoryName", "Category")">Click Me!</a> $("#renameCategory").on('click', function (evt) { //To prevent the link from sending the default request //call preventDefault() on the jQuery event object evt.preventDefault(); // if ($.trim($("#CategoryNewName").val()) == "") { alert("Please enter a category name"); return; } //GET THE URL FOR THE AJAX REQUEST var actionUrl = $(this).attr('href'); // var selectedCategory = $("#SelectedCategoryId").val(); var newCategoryName = $("#CategoryNewName").val(); var postData = { categoryId: selectedCategory, name: newCategoryName }; $.ajax({ type: "POST", url: actionUrl, data: postData, dataType: "json", success: function (data) { $('#' + selectedCategory).text(newCategoryName); $("#selectedCategoryText").html(newCategoryName); }, error: function () { alert('error') } }); });
You will also need to check for ajax requests in your controller, as shown below:
public ActionResult UpdateCategoryName() { ... if(Request.IsAjaxRequest()) { return Json(yourData); } return View(); }
That way, if your user has JavaScript turned off, the link will work like a normal HTTP request. If the user has JavaScript enabled, then they will gain Ajax experience. This is called graceful degradation
.
Paul source share