Ajax.ActionLink will not work if validation is false?

做~自己de王妃 提交于 2019-12-11 10:31:48

问题


@Ajax.ActionLink("like", "Like", "Article", new { postId = Model.post.PostId, userName = User.Identity.Name }, new AjaxOptions { OnBegin = "OnBegin" }, new { @class = "like_link" })

function OnBegin()
{
    if( true ) // value from client side. not returning value from server.
    {
        // I dont want to work the link. I want only alert message.
    }
    else
    {
        // Go to controller with parameters.
    }
}

I want something like above. OnBegin is not neccesary to do it. May be another solutions.

Thanks.


回答1:


OnBegin should do it. Simply return true or false depending on whether you want to execute the controller action or not:

function OnBegin() {
    if (true) // value from client side. not returning value from server.
    {
        // I dont want to work the link. I want only alert message.
        alert('alerting some message');
        return false;
    }
    else {
        // Go to controller with parameters.
        return true;
    }
}



回答2:


I'm reading this as you want the user to not be directed to the link's URL if the form is not valid. If that is the case, you could wire up to the link's click event, and do your validation check in javascript, then either let the user proceed if everything is valid, or stop it if the form is not valid. With jQuery, it would be something like this:

$(document).ready(function() {
    $('a.like_link').click(function (e) {
        if (formIsNotValid) { // Insert a real conditional here that works for your needs.
            e.preventDefault();

            // Display a message here?
        }

        // Don't need an else, everything is valid, let the user move on.
    });
});

Edit: if the user has javascript turned off, the link will work. Chances are, your validation wouldn't work in that case either.



来源:https://stackoverflow.com/questions/12359222/ajax-actionlink-will-not-work-if-validation-is-false

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!