1

离开我的 WPF 背景后,我正在学习 Asp.Net MVC。我基本上想单击一个按钮并更新我的模型而不刷新页面。我假设我可以以某种方式使用 AJAX 执行以下操作。

<input class="WelcomeButton" type="button" onclick="location.href='@Url.Action("SetGameType", "Welcome", new { gameType = GameTypes.Expert })'"/>

任何帮助都会很棒。

这是我看完Gent's Link后的进步

<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",

4

3 回答 3

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/

于 2012-08-12T02:48:06.677 回答
1

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

于 2012-08-12T10:21:22.007 回答
0

看起来您正在尝试做的是在不丢失当前页面状态的情况下调用服务器。如果是这样的话,而不是让您的 onclick 击中一个 URL,而是调用一个 javascript 方法,该方法将执行 ajax 发布。我建议阅读这个问题:jQuery Ajax POST example with PHP

于 2012-08-12T02:04:43.577 回答