[英]Call c# function with javascript code
我想从客户端调用函数背后的代码。 该函数不能是静态的-应该修改非静态的变量。 我能够创建一个不可见的按钮,当我需要该功能时,我演示了对该btn的单击。 如何将参数发送到函数背后的代码?
$.ajax({
url: '/ControllerName/ActionName',
type: "GET",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
}
});
这是客户端调用后端方法。 服务器端接受此请求:
public ActionResult ActionName(string param1)
{
return View(param1);
}
在这种情况下,我们使用了javascript插件jQuery,并使用了AJAX请求,还发送了参数。
使用MVC和jQuery
客户端(使用剃刀)
$.ajax({
url: '@Url.Action("ActionName","ControllerName",new{parameters})',
type: "GET",
contentType: "application/json",
data: { param1: val1 },
success: function (res) {
alert(res) // res is results that came from function
},
error: function (jqXHR, error, errorThrown) {
console.log('An error as occured');
},
});
服务器端
[HttpGet]
public JsonResult ActionName(string param1)
{
return Json(param1, JsonRequestBehavior.AllowGet);
}
注意:HttpGet动词是每个ActionResult / JsonResult的默认动词
该按钮具有CommandArgument
属性,您可以使用该属性将值发送给该函数,并且可以按以下方式读取它:
public void yourFunction(object sender,Eventargs e)
{
string args = ((LinkButton)sender).CommandArgument.ToString();
// rest of code here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.