How to call a Controller method from javascript in MVC3?

前端 未结 5 1913
栀梦
栀梦 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:41

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

    For Example:

    
    

    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.

提交回复
热议问题