Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a Controller method from javascript in MVC3?

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 thought to use onblur event to the User Id field which then calls the Controller method. Can any tell me how to approach to this problem? As Im a newbie, code snippets are highly appreciated.

Thanks in Advance,

Prashanth

like image 604
user1545987 Avatar asked Dec 12 '22 00:12

user1545987


1 Answers

Here is an example. Example of your Controller Method

[HttpPost] // can be HttpGet
public ActionResult Test(string id)
{
     bool isValid = yourcheckmethod(); //.. check
     var obj = new {
          valid = isValid
     };
     return Json(obj);
}

and this would be your javascript function.

function checkValidId(checkId)
{
    $.ajax({
         url: 'controllerName/Test',
         type: 'POST',
         contentType: 'application/json;',
         data: JSON.stringify({ id: checkId }),
         success: function (valid)
         {
              if(valid) { 
                  //show that id is valid 
              } else { 
                  //show that id is not valid 
              }
         }
    });
}
like image 69
Tom Kim Avatar answered Jan 07 '23 13:01

Tom Kim