How to call javascript function from controller in MVC3

I looked around and I can’t find a solution, so I am here. from what I read, I could do this in asp.net web forms using RegisterClientScript or RegisterClientScriptBlock. I cannot find this in any MVC3 documentation. I have the following function in MVC 3 View:

MyTest View:

<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>
 }

In My Controller, I have the following.

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();
    }
}
+3
source share
3 answers

"" Javascript . , , - RegisterClientScript, JS- , . ( , ), string. 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

, , ViewBag, :

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

// In the view:
<script type="text/javascript">
   @ViewBag.JS
+9

JavaScriptModel (http://jsm.codeplex.com) :

public ActionResult Index()
{
    this.AddJavaScriptFunction("addTableRow", "My Message");
    return View();
}

, js Tables js. js .

public ActionResult Index()
{
    this.AddJavaScriptVariable("TableListInJavaScript", tableList);
    this.AddJavaScriptFunction("MyTableReadyFunction");
    return View();
}
+2

, . javascript . - , javascript, ajax, jQuery- ajax, . $.post()

:

-:

$.post('TestController/TestGetPartialView','{param1:"string to add"}', function (data) {

    ('#mappingTable').append(data); // this adds the string to the mapping table.

},'html');

:

[HttpPost]
public PartialViewResult TestGetPartialView(string param1)
{   
   return PartialView("TestPartial", param1);
}

:

@model string
<p> Model </p>

, . , , , ajax , , , .

0

All Articles