2012-08-12 176 views
1

我正在学习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",

+0

你是什么意思的“它没有工作”。您的代码不包含任何传递给您的url的数据,并且在ajax调用完成时没有任何回调函数。截至目前这个代码,你怎么知道它是否工作? – 2012-08-12 03:21:56

回答

2

是的,如果你想做一个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/

+0

基本上我做了同样的事情。但都没有工作。 – MyKuLLSKI 2012-08-12 03:15:47

+0

没关系,它工作。因此,显然我所有使用JQuery的脚本都必须在创建元素之后......病态回到我的C编码模式:) – MyKuLLSKI 2012-08-12 03:23:18

+0

您可以将函数定义在按钮的click事件中,并在调用$ .ready( ),当文档被加载时触发。 http://api.jquery.com/ready/ – 2012-08-12 03:26:44

0

看起来你正在试图做的是调用服务器而不会丢失当前的页面状态。如果是这样的话,而不是让你的onclick击中一个URL,它会调用一个javascript方法,将做一个AJAX帖子。我推荐给这个问题读一下:jQuery Ajax POST example with PHP

1

看看knockoutJS,它的MVVM设计模式应该从您的WPF体验中熟悉。

+0

谢谢。我肯定会看看这个。 – MyKuLLSKI 2012-08-12 16:36:18