MVC中通过action方法点击按钮刷新内容

问题描述 投票:0回答:1

这是我的控制器。

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return Content(DateTime.Now.ToLongTimeString());
    }
}

这是我的观点。

<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $("input").click(function () {
        $("#div1").load('@Url.Action("Index")');
    });
</script>
<div id="div1"></div>
<input type="button" id="button1" value="Refresh"/>

运行项目后需要刷新当前时间。但运行项目后按钮没有显示。

如果我使用 F5 按钮刷新页面,时间就会刷新,但我想通过单击按钮来刷新。

javascript asp.net-mvc asp.net-mvc-4
1个回答
2
投票

您需要将脚本更改为

$( document ).ready(function() {
    $("#button1").click(function () {
        $("#div1").load('@Url.Action("Index")');
    });
});

以便它处理由

.click()
标识的按钮的
id="button1"
事件,并且您需要将脚本包装在准备好的文档中,因为您在脚本之后渲染元素(在解析脚本时它们不存在)风景)。或者,将脚本移动到紧邻结束
</body>
标记之前(元素之后)

© www.soinside.com 2019 - 2024. All rights reserved.