如何从MVC3中的javascript调用Controller方法?

我使用MVC3架构,c#.net。 当焦点更改为下一个字段即密码字段时,我需要立即将文本框内容(用户ID)与数据库进行比较。 所以我想在用户ID字段中使用onblur事件,然后调用Controller方法。 谁能告诉我如何处理这个问题? 作为一个新手,代码片段受到高度赞赏。

提前致谢,

普拉香特

这是一个例子。 控制器方法的示例

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

这将是你的javascript函数。

 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 } } }); } 

请参阅JQuery.get() , System.Web.Mvc.JsonResult 。

例如:

  

您需要一个操作来捕获GET请求:

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

几点,没有特别的顺序:

  • 请注意, .get的第一个参数是控制器操作的匹配URL?
  • #userID html字段的值附加到URL的末尾,允许MVC将数据绑定到操作参数ValidateUserID(string id)
  • Controller.Json方法将.NET对象格式化为JavaScript对象。 JQuery将格式化的对象作为回调函数中的data接收。
  • JsonRequestBehavior.AllowGet告诉MVC可以从.GET将数据传回浏览器。

这听起来像服务器端validation,因此您可以使用客户端validationfunction。

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

一般来说,这可以通过使用ajax调用来完成(不确定你是否使用jQuery,但如果没有,并且没有特殊限制,将鼓励使用它):

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

在客户端:

 $.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 } }); 

在服务器端:

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

但一般来说你应该从ASP.NET MVC 3 Ajax google,在网络上有很多相关内容,你可能已经找到了你需要的东西。

您可以在控制器上使用带有服务器端操作的RemoteValidation属性,通过MVC Unobstrusive javascript为您完成所有操作,而不需要为它编写单行JS / Jquery。

这是你能做的:

鉴于您有一个名为AccountController控制器和一个名为CheckPassword ,它接受参数string password ,您可以将它放在您的视图中:

 $('#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'); } }); }); 

您的控制器操作大致如下所示:

 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); } }