gpt4 book ai didi

asp.net-mvc-3 - 如何从 MVC3 中的 Controller 调用 javascript 函数

转载 作者:行者123 更新时间:2023-12-02 20:01:41 26 4
gpt4 key购买 nike

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

我的测试 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>
}

在我的 Controller 中,我有以下内容。

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();
}
}

最佳答案

您无法真正从 Controller “调用”客户端 Javascript。假设您想要执行类似于 RegisterClientScript 的操作(将 JS 代码注入(inject)到您的页面中),那么您可以轻松完成。您可以创建一个具有字符串属性的模型(只不过是一个简单的类)。将属性值设置为要注入(inject)的客户端 JS 代码。将模型传递给 View 。在您的 View 中,引用该属性 - 如下所示:

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

关于asp.net-mvc-3 - 如何从 MVC3 中的 Controller 调用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10166235/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com