MVC3从JavaScript调用控制器方法 [英] MVC3 Calling controller method from Javascript
问题描述
在MVC3。我有一个按钮类开放式deleteRowDialog当我点击它进入这个JavaScript:
In MVC3. I have a button class"open-deleteRowDialog" when i click on it goes to this javascript:
$(document).on("click", ".open-DeleteRowDialog", function () {
var pwd= '@Url.("GeneratePsw","Admin")';
$(".modal-body #pwd").val(pwd);
$('#1').modal('show');
})
我想是调用一个方法(在控制器),谁拥有返回一个字符串,that's我想要的VAR PWD保存在一个模型来显示(视图)
what i want is to call a method (in controller), who has to return a string, that´s what i want to save in "var pwd" to show in a model (view)
(在控制器)的方法是:
the method (in controller) is:
public string GeneratePsw()
{
HomeBridgeEntities ddbb = new HomeBridgeEntities();
SqlConnection Cn = new SqlConnection(((System.Data.EntityClient.EntityConnection)ddbb.Connection).StoreConnection.ConnectionString);
SupPassGenerator sup = new SupPassGenerator(Cn);
//psw conteins a password from CreateRandomPassword
string psw = sup.CreateRandomPassword(9);
return psw;
}
谢谢!
推荐答案
请在 AJAX 拨打你的控制器的操作方法。您可以使用 $。获得
法像下面。
Make an ajax call to your controller action method. You may use $.get
method like below.
$(function(){
$(document).on("click", ".open-DeleteRowDialog", function () {
var pwd="";
$.get("@Url.Action("Yourcontroller","GeneratePsw")",function(data){
pwd=data;
//now do whatever you want with pwd variable;
});
})
});
$不用彷徨是 $。阿贾克斯$ C $的简写形式C>法类型HTTP GET。
$.get is a short form of $.ajax
method with type HTTP GET.
如果你有一个像在响应缓存数据的麻烦,你可能在你的 GET
调用添加了独特的时间戳,这样你就不会获得缓存的结果。您可以使用 $。现在方法。
If you have trouble like cached data in the response, you may add a unique timestamp in your get
call so that you won't get the cached result. You may use $.now method.
$.get("@Url.Action("Yourcontroller","GeneratePsw")?"+$.now(),function(data){
// to do : do something with result
});
另一种方法是设置 ajaxSetup 方法缓存属性值设置为false。但是,这将适用于所有的Ajax调用。
Another way is to set the cache property value to false in ajaxSetup method. But this will be applicable to all ajax calls.
这篇关于MVC3从JavaScript调用控制器方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!