如何在MVC中单击一下按钮调用javascript函数和C#函数

时间:2014-03-11 10:04:00

标签: c# javascript jquery asp.net-mvc

我想使用单击按钮调用一个javascript和一个用Model Class编写的函数。我使用了以下代码:

<script language="javascript" type="text/javascript">
    function RunEXE() {
        var txtfile = document.getElementById("txtFileName");
        //var txtProgram = document.getElementById("txtProgram");
        //if ((!String.IsNullOrEmpty(txtfile)) && (!String.IsNullOrWhiteSpace(txtProgram))) {
        if (txtfile.value != "") {
            var oShell = new ActiveXObject("WScript.Shell");
            //var prog = "c:\\Pgms\\sample0.exe";

            var prog = "\\\\Test-PC\\Programms\\" + txtfile.value + ".exe";
            oShell.Run('"' + prog + '"', 1);
        } else {
            alert('The file name must be entered in file name textbox');

        }
    }
    </script>

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

以下代码是模型功能:

public ActionResult Run(UserProgram userProgram)
    {
        SaveAndCompile(userProgram);
        return null;
    }

但它单独使用Run()而不是运行RunEXE()

2 个答案:

答案 0 :(得分:1)

[HttpPost]

public ActionResult RunAction(string option1) {     //如果需要,您可以使用“option1”值来确定要传递的UserProgram     UserProgram userProgram = new UserProgram();     运行(userProgram);

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

}

$.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"
  }

);

答案 1 :(得分:0)

在您的情况下,您可以通过JQuery提交功能提交表单。

我假设你的代码如下:

<form id="form" action="/Run">
// your some inputs
<input type="submit" name="button" value="Run" />
</form>

提交的javascript将是:

$(function() {
    $('#form').submit(function() {
        // to do something before the form is submitted
        RunEXE();
        return true; // return false to cancel form action
    });
});

干杯。