2

我最近注意到 MVCAjax.BeginForm在返回视图时表现得很奇怪。起初一切看起来都很好,但后来我意识到在 document ready 中发生的所有绑定都丢失了。文档就绪未执行。

知道这在其他地方也有效,我发现用 jquery get 做同样的事情确实可以执行文档。但据我了解,这两种方法基本上是在做同样的事情。我的快速解决方法是去掉助手的 Replace TargetId 实现并使用它AjaxOptions.OnSuccess来调用我的jquery.get()实现。

但是为什么在我使用时 document ready 会触发jquery.get(),而不是在我使用Ajax.BeginForm替换 a时会触发div


// This method returns a the partial view from DoSomething, but DOES NOT execute the 
// partial view's document.ready
using (Ajax.BeginForm("DoSomething", "Somewhere", new AjaxOptions { HttpMethod = "Post", InsertionMode = InsertionMode.Replace, UpdateTargetId = "demo" }))
{ %>
    <div id="demo"></div>
<% } %>

示例 1. 用于替换 div 的 MVC Helper 方法


// This method returns nothing from DoSomething, calls getSomething onSuccess and DOES 
// execute the partial view's document.ready
using (Ajax.BeginForm("DoSomething", "Somewhere", new AjaxOptions { HttpMethod = "Post", OnSuccess = "function() { getSomething(); }" }))
{ %>
    <div id="demo"></div>
<% } %>

// this being the simplified js function
function getSomething(){
    var $targetDiv = $("#demo");
    var url = "<%: Url.Action("LoadSomething", "Somewhere")  %>";
    $.get(url, { }, function (result) { $targetDiv.html(result) });
});

示例 2. jquery.get() 替换 div 的方法

4

1 回答 1

2

我可以建议如何在没有 JavaScript 代码的情况下构建丰富的应用程序的替代方法,例如 Ajax.BeginForm,但更具灵活性和可定制性。

示例:从控制器获取 html 并插入到 dom 元素中。

<div id="containerId"></div>
 @(Html.When(JqueryBind.Click)
       .Do()
       .AjaxGet(Url.Action("GetContent", "SomeController"))
       .OnSuccess(dsl => dsl.With(r=> r.Id("containerId"))
                            .Core()
                            .Insert
                            .Html())
       .AsHtmlAttributes()
       .ToButton("Insert button"))

您使用任何 dom 值来请求请求,例如

AjaxGet(Url.Action("GetContent", "SomeController",new 
                                       {
                                         Criterie=Selector.Jquery.Name("txtName")
                                        } ))

您可以在官方文档中查看示例并从 github下载示例项目示例。

于 2013-09-22T07:22:37.797 回答