c# - PartialView 在 ajax 重新加载时无法正确呈现

标签 c# ajax asp.net-mvc kendo-asp.net-mvc

我在使用 ajax 重新加载局部 View 时遇到问题。

我在局部 View 中有我的国家/地区表单,最初当我加载主页时,一切都正确呈现。

如下图所示,我可以使用自动完成功能搜索国家/地区,也可以从组合框中选择国家/地区(两者都是 kendo-mvc 控件)

enter image description here

当我从自动完成中选择一个并尝试通过 ajax 加载所选国家/地区的信息时,问题就出现了。表单已重新加载,信息已显示,但控件未正确呈现。自动完成功能停止工作,组合框呈现为普通文本框,显示 CountryID 而不是国家/地区名称。

enter image description here

代码在我看来

@using (Html.BeginForm("Index", "CountryManagement", FormMethod.Post, new { id = "country-form" }))
{  
    @Html.ValidationSummary(true);
    <div id="form-content">
         @Html.Partial("_CountryForm", Model)
    </div>

}

我的部分 View 中的代码

<div class="form-group">
        @Html.Label("Search Country", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-3">
            @(Html.Kendo().AutoCompleteFor(m => m.Search)
                          .DataTextField("Designation")
                          //.DataValueField("CountryID")
                          .Filter("contains")
                          .MinLength(2)
                          .DataSource(d => { d.Read(r => r.Action("SearchCountry", "Common")); })
                          .Events(e => e.Change("onChange")).Deferred()
            )
        </div>
    </div>

Controller 中的代码

[HttpPost]
public PartialViewResult Edit(int id)
{
    //HTTP GET: api/Country/CountryDetails?id={id}&lang={lang}
    dynamic model =  //code to get selcted country data
    return PartialView("_CountryForm", model);
}

我的 .js 文件中的代码

function onChange() {
    
    if ($("#Search").data("handler")) {
        var data = $("#Search").data("handler").dataSource.data();
        var country = data.find(x => x.Designation == $("#Search").val());
        console.log("Country")
        if (country) {
            var request = $.post('/CountryManagement/Edit', { id: country.CountryID });
            request.success(function (data) {
                $("#form-content").html(data);
            });
        }
    }
}

页面加载时生成的 HTML 代码(仅限自动完成和下拉菜单)

<div class="form-group">
    <label class="control-label col-md-2" for="Search_Country">Search Country</label>
    <div class="col-md-3">
        <span tabindex="-1" role="presentation" class="k-widget k-autocomplete k-header k-state-default k-state-hover"><input data-val="true" data-val-length="Description  must have between 1  and 150 characters" data-val-length-max="150" data-val-length-min="1" id="Search" name="Search" type="text" data-role="autocomplete" class="k-input" autocomplete="off" role="textbox" aria-haspopup="true" aria-disabled="false" aria-readonly="false" aria-owns="Search_listbox" aria-autocomplete="list" has-focus="false" style="width: 100%;"><span class="k-icon k-loading" style="display:none"></span></span>
    </div>
</div>
<br>
<br>
<div class="form-group">
    <label class="control-label col-md-2" for="Country">Country</label>
    <div class="col-md-3">
       <span class="k-widget k-combobox k-header"><span tabindex="-1" unselectable="on" class="k-dropdown-wrap k-state-default"><input name="CountryID_input" class="k-input" type="text" autocomplete="off" title="" role="combobox" aria-expanded="false" tabindex="0" aria-disabled="false" aria-readonly="false" aria-autocomplete="list" aria-owns="CountryID_listbox" has-focus="false" style="width: 100%;"><span tabindex="-1" unselectable="on" class="k-select"><span unselectable="on" class="k-icon k-i-arrow-s" role="button" tabindex="-1" aria-controls="CountryID_listbox">select</span></span></span><input data-val="true" data-val-number="The field CountryID must be a number." id="CountryID" name="CountryID" type="text" value="0" data-role="combobox" aria-disabled="false" aria-readonly="false" has-focus="false" style="display: none;"></span>
        <span class="field-validation-valid text-danger" data-valmsg-for="CountryID" data-valmsg-replace="true"></span>
    </div>
</div>

在部分 View 重新加载时生成的 HTML 代码(仅限自动完成和下拉)

<div class="form-group">
    <label class="control-label col-md-2" for="Search_Country">Search Country</label>
    <div class="col-md-3">
        <input data-val="true" data-val-length="Description  must have between 1  and 150 characters" data-val-length-max="150" data-val-length-min="1" id="Search" name="Search" type="text" value="South Africa">
    </div>
</div>
<br>
<br>
<div class="form-group">
    <label class="control-label col-md-2" for="Country">Country</label>
    <div class="col-md-3">
       <input data-val="true" data-val-number="The field CountryID must be a number." id="CountryID" name="CountryID" type="text" value="1003">
        <span class="field-validation-valid text-danger" data-valmsg-for="CountryID" data-valmsg-replace="true"></span>
    </div>
</div>

我不确定这是否是 ASP.Net MVC 局部 View 、Kendo 控件或某些应在局部 View 重新加载时重新运行的脚本的问题。 有人可以帮帮我吗?

最佳答案

经过无数次失败的尝试和在 Telerik 论坛深处的挖掘无果后,我终于找到了问题所在。

部分 View 中的 Kendo 小部件不应使用延迟初始化。

@(Html.Kendo().AutoCompleteFor(m => m.Search)
                      ///.. code removed to reduce complexity
                      .Events(e => e.Change("onChange")).Deferred()
 )

当 View 作为服务器请求加载时,它会正确呈现,因为在布局文件的末尾,所有具有延迟初始化的小部件都使用 @Html.Kendo().DeferredScripts()。然而,当通过 ajax 重新加载局部 View 时,延迟的脚本初始化永远不会发生,因为脚本不会重新运行。

@Html.Kendo().DeferredScripts() 添加到局部 View 解决了 ajax 重新加载的问题,但在服务器加载时成为问题,因为:1 - 延迟初始化将运行两次,和 2 - 因为 kendo 小部件具有 jquery 依赖项,并且会在页面中包含 jquery 脚本之前运行。

我找到的解决方案是不延迟小部件的初始化,但是这会让我们回到上面关于 jquery 依赖项的观点。尽管我尽量避免它,但唯一真正有效的方法是在页眉中包含 jquery。所有其他脚本(验证、剑道、自定义等)仍在底部,但主要的 jquery 脚本在顶部。现在我的部分 View 可以完美地加载到服务器或 ajax 请求上。

长话短说;

  1. 不要在部分 View 中使用延迟初始化
  2. 将 jquery.min.js 移至页面顶部。

希望有更好的方法来做到这一点,但目前它可以解决问题。

关于c# - PartialView 在 ajax 重新加载时无法正确呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38391225/

相关文章:

c# - 为 S3 设计

asp.net - 如何获取共享 error.cshtml 的异常详细信息

c# - 使用泛型类型 'IdentityUserRole<TKey>' 需要 1 个类型参数

c# - 带返回值的递归函数VS使用OUT参数

c# - 直到运行时才知道属性的匿名类型

php - 如何通过 Ajax 将文件从 JavaScript 传输到 PHP

c# - 如何处理复选框列表?

c# - 将 Owin/Katana 与 ASP.NET Core(实际用例)一起使用是否仍然相关?

javascript - 如何正确使用AJAX和express

php - AJAX + jQuery 变量不传递给 PHP