5

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

Jesse Hallam
6,9548 gold badges52 silver badges71 bronze badges
asked Jul 25, 2012 at 7:25
1
  • Does you controller method return a JsonResult? Commented Jul 25, 2012 at 7:27

5 Answers 5

10

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 
 }
 }
 });
}
answered Jul 25, 2012 at 7:39
1
  • Thanks to EveryOne!! I got it. I'm so happy :-) Commented Jul 25, 2012 at 8:57
2

It sounds like server side validation, so may be you can use client side validation features for this.

http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

In general, that may be done by using ajax call (not sure if you're using jQuery, but if not and there's no special limitations, would encourage to use it for this):

http://api.jquery.com/jQuery.ajax/

On client side:

$.ajax({
 url: '@Url.Action("ActionName", "ControllerName")',
 type: "POST",
 async: true,
 dataType: "json",
 data: $('#form').serialize(), 
 success: function (data) {
 // process result
 },
 error: function (request, status, error) {
 // process error message
 }
 });

On server side:

[HttpPost]
public virtual ActionResult ActionName() 
{
 return Json("value")
}

But in general you should google from ASP.NET MVC 3 Ajax, there's plenty stuff regarding this in web and you may find exactly what you need already.

answered Jul 25, 2012 at 7:27
3
  • Im using Jquery too. Pls tell me how how to call the method using jquery. Commented Jul 25, 2012 at 7:29
  • Since you are sending request via 'post' verb, there is no need in JsonRequestBehavior.AllowGet parameter, is there? Commented Jul 25, 2012 at 7:36
  • @user1545987 updated with some snipped, but in general I think you're trying to validate user name/password, if it is that so, you should really use validation framework, that is already there. Commented Jul 25, 2012 at 7:40
2

See JQuery.get(), System.Web.Mvc.JsonResult.

For Example:

<script type="text/javascript">
 $('#userID').blur(function()
 {
 $.get('/Home/ValidateUserID/' + $(this).val(), {}, 
 function(data, status)
 {
 if( !data.success ) {
 alert('User ID is invalid!');
 }
 });
 });
</script>

You'll need an action to catch the GET request:

public class HomeController
{
 [HttpGet]
 public ActionResult ValidateUserID(string id)
 {
 bool superficialCheck = true;
 return Json(new { success = superficialCheck },
 JsonRequestBehavior.AllowGet);
 }
}

A few points, in no particular order:

  • Notice that the first parameter to .get is the matching URL to the controller action?
  • The value of the #userID html field is appended to the end of the URL, allowing MVC to data bind it in to the action parameters ValidateUserID(string id).
  • The Controller.Json method formats .NET objects as JavaScript objects. The formatted object is recieved by JQuery as data in the callback function.
  • JsonRequestBehavior.AllowGet tells MVC that its okay to pass data back to the browser from a .GET.
answered Jul 25, 2012 at 7:39
2

You can use RemoteValidation attribute with a server side action on your controller to do it for you all by MVC Unobstrusive javascript and not needed to write a single line JS/Jquery for it.

answered Jul 25, 2012 at 8:00
0

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);
 }
}
answered Jul 25, 2012 at 7:46

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.