I have looked round and I cannot find a solutions hence I find myself here. from what i have read i would been able to 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 a 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();
}
}
You can't really "call" the client Javascript from the controller. What you can do, assuming you want to do something analogous to RegisterClientScript which is injecting JS code into your page, can be done pretty easily. You can either create a model (which is nothing more than a simple class) that has a string property on it. Set the property value to the client-side JS code that you want to inject. Pass the model to the view. In your View, reference the property - something like this:
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
Or, if you don't want to create model, you can pass it via the ViewBag, which is a dynamic object:
public ActionResult Index()
{
ViewBag.JS = "addTableRow('My Message');";
return View();
}
// In the view:
<script type="text/javascript">
@ViewBag.JS
With JavaScriptModel ( http://jsm.codeplex.com ) you could do it the following way:
public ActionResult Index()
{
this.AddJavaScriptFunction("addTableRow", "My Message");
return View();
}
It would be even better if you create a js-file with a function and add the Tables as list to a js variable. The js function will then iterate over the list and add the tables.
public ActionResult Index()
{
this.AddJavaScriptVariable("TableListInJavaScript", tableList);
this.AddJavaScriptFunction("MyTableReadyFunction");
return View();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With