How to call a Controller method from javascript in MVC3?

前端 未结 5 1927
栀梦
栀梦 2021-01-01 05:52

Im using MVC3 architecture, c#.net. I need to compare text box content(User ID) with the database immediately when focus changes to the next field i.e., Password field. So I

5条回答
  •  一个人的身影
    2021-01-01 06:23

    here is what you could do:

    Given that you have controller called AccountController and action called CheckPassword that accepts parameter string password, you could put this in your view:

    $('#texboxId').blur(function() {
        $.ajax({
            url: '/Account/CheckPassword',
            data: { password: $('#texboxId').val() },
            success: function(data) {
                // put result of action into element with class "result"
                $('.result').html(data);
            },
            error: function(){
                alert('Error');
            }
        });
    });
    

    Your controller action would approximately look like this:

    public class AccountController : Controller
    {
        public ActionResult CheckPassword(string password)
        {
            bool passwordIsCorrect = //do your checking;
            string returnString = "whatever message you want to send back";
            return Content(returnString);
        }
    }
    

提交回复
热议问题