如何从MVC3中的控制器调用javascript函数

use*_*414 3 asp.net-mvc-3

我环顾四周,找不到解决方案,因此我发现自己在这里.根据我的阅读,我可以使用RegisterClientScript或RegisterClientScriptBlock在asp.net Web表单中执行此操作.我在任何MVC3文档中都找不到这个.我在MVC 3视图中有以下功能:

MyTest查看:

<div data-role="content">

<div id="mappingTable"></div>

</div>

 </section>
 @section Scripts {
 <script type="text/javascript">

    $("#jqm-home").live('pageinit', function () {
        addTableRow(' adding data to table <br/>');
    });

    //I want to the able to call the function from the controller.
    function addTableRow(msg) {
        $('#mappingTable').append(msg);        
    }; 

   </script>
 }
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,我有以下内容.

public class MyTestController : Controller
    {
      #region Class Constractor

       public MyTestController()
       {            
           Common.ControllerResourceEvent += new System.EventHandler<ResourceEventArgs>(Common_ResourceEvent);
       }

    private void Common_ResourceEvent(object sender, ResourceEventArgs e)
    {
        //I want to call the function addTableRow and pass ResourceEventArgs 
    } 

    #endregion Class Constractor      

    public ActionResult Index()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*ski 9

你无法真正从控制器"调用"客户端Javascript.你可以做的,假设你想做一些类似于RegisterClientScript的东西,它将JS代码注入你的页面,可以很容易地完成.您可以创建一个模型(它只不过是一个简单的类),它上面有一个字符串属性.将属性值设置为要注入的客户端JS代码.将模型传递给视图.在您的视图中,引用该属性 - 如下所示:

public class SampleModel
{
   public string JS { get; set; }
}

public ActionResult Index()
{
    var model = new SampleModel();
    model.JS = "addTableRow('My Message');";
    return View(model);
}

// In the view (at the top - note the cast of "model" and "Model"
@model Namespace.SampleModel
// Then your script 
<script type="text/javascript">
   @Model.JS
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想创建模型,可以通过ViewBag传递它,ViewBag是一个动态对象:

public ActionResult Index()
{
    ViewBag.JS = "addTableRow('My Message');";
    return View();
}

// In the view:
<script type="text/javascript">
   @ViewBag.JS
Run Code Online (Sandbox Code Playgroud)

  • `@ViewBag.JS` 可能会导致语法错误。如果是这种情况,请尝试`@Html.Raw(ViewBag.JS)` (2认同)