在asp.net MVC中,部分视图不能与ms ajax一起更新

本文关键字:不能 ms ajax 更新 一起 视图 net asp MVC | 更新日期: 2023-09-27 18:14:02

我有一个搜索文本框和一个按钮。我想在单击按钮时用ajax在部分视图中显示搜索结果。当我在局部视图中设置断点时,我可以看到数据,但表单上什么也没有显示。

传递搜索文本值的控制器:

[HttpPost]
        public async Task<ActionResult> Index(string searchtext)
        {
            // search data and put it in Results here ...
            ViewBag.Results = Results;
            return PartialView("_SearchResults");
        }

我的指数。CSHTML视图代码:

@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm())
{
    <input autofocus="autofocus" class="form-control" id="SearchStr" name="SearchStr" placeholder="search" required="required" title="Search" type="search" value="">
    @Html.SubmitButton("Search", "btnSearch")
    <div id="resultsDiv">
        @using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.InsertAfter, UpdateTargetId = "resultsDiv" }))
        {
            <p>hre</p>
        }
    </div>
}

@section scripts
{
    <script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
    <script>
        $("#btnSearch").on("click", function (e) {
            e.preventDefault();
            $.ajax({
                type: "post",
                datatype: "json",
                url: "/Home/Index",
                data: {
                    searchtext: document.getElementById("SearchStr").value
                }
            });
        });
    </script>
}

,这是我的部分观点,在断点,我可以看到51个数的结果…

@if (ViewBag.Results != null)
{
    foreach (var person in ViewBag.Results.Data)
    {
        <div>
            <p>
                @person.FullName
            </p>
        </div>
    }
}

我在编译和运行时没有错误,在浏览器中没有错误…

视频

在asp.net MVC中,部分视图不能与ms ajax一起更新

试试这个

    <div id="resultsDiv"> </div>
    @using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "post", InsertionMode = InsertionMode.InsertAfter, UpdateTargetId = "resultsDiv" }))
    {
        <p>hre</p>
    }

resultsDiv将在完成ajax调用后更新

还要确保你的foreach循环数据

    foreach (var person in ViewBag.Results.Data)
{
    <div>
        <p>
            @person.FullName
        </p>
    </div>
}