C# 如何从 MVC3 中的 javascript 调用控制器方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11644658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a Controller method from javascript in MVC3?
提问by user1545987
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.
我使用 MVC3 架构,c#.net。当焦点更改到下一个字段即密码字段时,我需要立即将文本框内容(用户 ID)与数据库进行比较。所以我想对 User Id 字段使用 onblur 事件,然后调用 Controller 方法。谁能告诉我如何解决这个问题?由于我是新手,非常感谢代码片段。
Thanks in Advance,
提前致谢,
Prashanth
普拉尚特
采纳答案by Tom Kim
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.
这将是您的 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
}
}
});
}
回答by Giedrius
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
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):
一般来说,这可以通过使用 ajax 调用来完成(不确定您是否使用 jQuery,但如果没有并且没有特殊限制,鼓励使用它):
http://api.jquery.com/jQuery.ajax/
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.
但总的来说,你应该从 ASP.NET MVC 3 Ajax 谷歌搜索,网络中有很多关于这个的东西,你可能已经找到了你需要的东西。
回答by Jesse Hallam
See JQuery.get(), System.Web.Mvc.JsonResult.
请参阅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:
您需要一个操作来捕获 GET 请求:
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
.getis the matching URL to the controller action? - The value of the
#userIDhtml field is appended to the end of the URL, allowing MVC to data bind it in to the action parametersValidateUserID(string id). - The
Controller.Jsonmethod formats .NET objects as JavaScript objects. The formatted object is recieved by JQuery asdatain the callback function. JsonRequestBehavior.AllowGettells MVC that its okay to pass data back to the browser from a.GET.
- 请注意,第一个参数 to
.get是控制器操作的匹配 URL? - 所述的值
#userIDHTML字段被附加到URL的末尾,允许MVC中的动作参数数据绑定它ValidateUserID(string id)。 - 该
Controller.Json方法将 .NET 对象格式化为 JavaScript 对象。格式化的对象由 JQuery 接收,就像data在回调函数中一样。 JsonRequestBehavior.AllowGet告诉 MVC 可以将数据从.GET.
回答by Dmitry Efimenko
here is what you could do:
这是你可以做的:
Given that you have controller called AccountControllerand action called CheckPasswordthat accepts parameter string password, you could put this in your view:
鉴于您调用了控制器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');
}
});
});
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);
}
}
回答by Furqan Hameedi
You can use RemoteValidation attribute with a server side action on your controllerto do it for you all by MVC Unobstrusive javascript and not needed to write a single line JS/Jquery for it.
您可以将RemoteValidation 属性与控制器上的服务器端操作一起使用,通过 MVC Unobtrusive javascript 为您完成所有操作,而无需为其编写单行 JS/Jquery。

