Uthman Rahimi Uthman Rahimi - 7 months ago 139
Javascript Question

OnClick does not work to Preventt in ActionLink -ASP.NET MVC

I have a ActionLink Like this :

@Html.ActionLink("Add New", MVC.Admin.Purchase.Create(), new { @class = "btn btn-success", onclick = "return checkDefaultStore();" })


html result above code is :

<a class="btn btn-sm btn-success" href="/Admin/Purchase/Create" onclick="return checkDefaultStore();">Add New</a>


I want before go to new Page check a something and if that not exists prevent to go to new page .

For this I create this JQuery function :

function checkDefaultStore(e) {
var url = $('#ajax-info').data('checkdefaultstore');
$.ajax({
url: url,
data: {},
type: 'POST',
success: function (data) {
if (data.result)
return true;
else
return false;
},
error: function (response) {

}
});
}


Action method which defined return
false
or
true
.

[HttpPost]
public virtual JsonResult HasDefault()
{
bool result = _storeService.HasDefault();
if (result)
return Json(new { result = true },JsonRequestBehavior.AllowGet);
else
return Json(new { result = false, message = "default store does not exists" },JsonRequestBehavior.AllowGet);
}


when click on link , it calls function and go to new Page.

Answer

Your link will always redirect because ajax calls are async and by the time your controller returns the result, the browser has already redirected to the other page.

You options are (in order of preference)

  1. Check the value of _storeService.HasDefault() in the GET method that generates your view, and if false, then do not generate the link in the first place (no script required).
  2. Remove the onclick from the link and just let it redirect to your Create() method. In that method check the value of _storeService.HasDefault() and if false, return the view with the error message (no script required)
  3. Make the redirect in the ajax success callback using location.href. You code would be
    <a href="#" id="create">Add New</a>

    $('#create').click(function() {
        var url = $('#ajax-info').data('checkdefaultstore');
        $.post(url, function(data) {
            if (data.result)
                location.href = '@Url.Action("Create", "Purchase", new { area = "Admin" }';
            else
                alert(data.message);
            }
        });
    });