我环顾四周,找不到解决方案,因此我发现自己在这里。根据我所读到的内容,我可以使用 RegisterClientScript 或 RegisterClientScriptBlock 在 ASP.NET Web 表单中执行此操作。我在任何 MVC3 文档中都找不到这个。
我在 MVC 3 视图中有以下功能:
我的测试视图:
<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>
}
在我的控制器中我有以下内容。
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();
}
}
您无法真正从控制器“调用”客户端 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
或者,如果您不想创建模型,您可以通过 ViewBag 传递它,这是一个动态对象:
public ActionResult Index()
{
ViewBag.JS = "addTableRow('My Message');";
return View();
}
// In the view:
<script type="text/javascript">
@ViewBag.JS
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)