Asp.net MVC使用AJAX不刷新页面
问题描述:
我正在学习Asp.Net MVC的过程中脱离我的WPF背景后。我基本上想单击按钮并更新我的模型而不刷新页面。我假设我可以用AJAX以某种方式执行以下操作。Asp.net MVC使用AJAX不刷新页面
<input class="WelcomeButton" type="button" onclick="location.href='@Url.Action("SetGameType", "Welcome", new { gameType = GameTypes.Expert })'"/>
任何帮助将是巨大的。
这是在寻找根特的链接后,我的进步
<input class="WelcomeButton" id="NoviceButton" type="button" style="left: 157px; top: 442px;"/>
$("#NoviceButton").click(function(){
$.ajax({
url: "@Url.Action("TestMethod", "Welcome")",
type: "post"
});
});
我有一个按钮,提交和没有表单中的按钮......无论哪种方式上面没有与URL或这方面的工作一个url: "\Welcome\TestMethod",
答
是的,如果你想做一个AJAX请求,你可能想使用一个JavaScript框架。 ASP.NET MVC附带了JQuery,所以这个例子假设你已经准备好了JQuery。
<button id="MyButton" />
<script type="text/javascript">
// This will bind a javascript event handler to the button(s) identified
// by the CSS selector #MyButton.
//
// You could also use the onclick event in the <input> element to
// say, call a javascript function... but this couples the HTML to
// the Javascript logic in a way that is less maintainable as things
// get more complex.
$("#MyButton").click(function() {
// $ is a global reference to JQuery. This instantiates and executes
// a JQuery request using the browsers native request object (different
// browsers do this slightly differently, this is why you need a
// framework like JQuery to write Javascript productively)
$.ajax(
// This is the URL back to an ASP.NET controller\action that will handle the event.
url: "{controller}/{action}",
// This is a callback function that will execute when the round trip completes.
success: function (response) {
alert("server response: " + response);
}
);
});
</script>
欢迎来到网络编程的世界。 http://api.jquery.com/jQuery.ajax/
答
看起来你正在试图做的是调用服务器而不会丢失当前的页面状态。如果是这样的话,而不是让你的onclick击中一个URL,它会调用一个javascript方法,将做一个AJAX帖子。我推荐给这个问题读一下:jQuery Ajax POST example with PHP
你是什么意思的“它没有工作”。您的代码不包含任何传递给您的url的数据,并且在ajax调用完成时没有任何回调函数。截至目前这个代码,你怎么知道它是否工作? – 2012-08-12 03:21:56