从JavaScript调用的方法在MVC [英] Calling method from javascript in MVC

查看:157
本文介绍了从JavaScript调用的方法在MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从JavaScript调用一个控制器方法。我用下面的code:

I want to call a controller method from Javascript. I used the following code:

<input type="submit" name="button" value="Run" onclick="RunEXE"/>

我想写的JavaScript来调用控制器下面的功能。

I want to write the javascript to call the below function in controller.

public void Run(UserProgram userProgram)
    {
        SaveAndCompile(userProgram);
    }

任何人都可以向我提供的JavaScript调用的函数。

Can anyone provide me the javascript to call the function.

推荐答案

您不能只是调用这样的功能。你需要了解的是,JavaScript的运行在客户机上,你的作用是在服务器上。你需要做的是向服务器请求,就像你会加载一个页面时,所以对于这一点,你需要一个动作(确保它是一个POST操作当我们将张贴的要求)。这个动作可以短至只调用你需要的功能:

You can't just call a function like that. What you need to understand is that javascript runs on the client, and your function is on the server. What you need to do is make a request to the server, just like you would when loading a page, so for this you need an Action (make sure it is a POST action as we will be "posting" the request). This action can be as short as just calling the function you need:

[HttpPost]
public ActionResult RunAction(string option1)
{
    //if needed, you can use the "option1" value to determine the UserProgram to pass
    UserProgram userProgram = new UserProgram();
    Run(userProgram);

    //you can return a JSON reuslt that you can evaluate back at the client
    return Json(new { @Success = true, @MyString = "a string" });
}

然后,你要使用AJAX调用从客户端(JavaScript)的功能,为了这个,我会建议 JQuery的因为它使事情变得更容易使用

Then you want to use ajax to call the function from the client (javascript), for this I would recommend JQuery as it makes things much easier using post:

$.post('@Url.Action("RunAction", "MyController")',
      {
         option1: "some optional value"
      },
      function (data) {
          alert("success!");
          //here you have access to your JSON result via data, for example:
          //data.Success = true
          //data.MyString = "a string"
      }
);

这篇关于从JavaScript调用的方法在MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆