简体   繁体   English

用JavaScript代码调用C#函数

[英]Call c# function with javascript code

I would like to call a code behind function from the client side. 我想从客户端调用函数背后的代码。 The function cannot be static - should modified unstatic variabels. 该函数不能是静态的-应该修改非静态的变量。 I was able to create a non-visible button, and when I need that function I demonstrate a click on that btn. 我能够创建一个不可见的按钮,当我需要该功能时,我演示了对该btn的单击。 How can I send parameters to that code behind function? 如何将参数发送到函数背后的代码?

$.ajax({
    url: '/ControllerName/ActionName',
    type: "GET",
    data: { param1: val1 },
    success: function (res) {
        alert(res) // res is results that came from function
    }
});

This is the client side to call backend method. 这是客户端调用后端方法。 The server side to accept this request: 服务器端接受此请求:

    public ActionResult ActionName(string param1)
    {
        return View(param1);
    }

In this case, we used jQuery, the javascript plugin, and we used AJAX request, also sending parameters. 在这种情况下,我们使用了javascript插件jQuery,并使用了AJAX请求,还发送了参数。

Using MVC and jQuery 使用MVC和jQuery

Client Side ( Using Razor ) 客户端(使用剃刀)

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

Server Side 服务器端

[HttpGet]
public JsonResult ActionName(string param1)
{
     return Json(param1, JsonRequestBehavior.AllowGet);
}

Note: HttpGet Verb is the default verb for every ActionResult/JsonResult 注意:HttpGet动词是每个ActionResult / JsonResult的默认动词

the button have a CommandArgument attribute that you can use to send a value to that function and you can read it as follow : 该按钮具有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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM