繁体   English   中英

部分视图不会在 asp.net MVC 中使用 ms ajax 更新

[英]Partial view does not Update with ms ajax in asp.net MVC

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

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

[HttpPost]
        public async Task<ActionResult> Index(string searchtext)
        {

            // search data and put it in Results here ...
            ViewBag.Results = Results;

            return PartialView("_SearchResults");
        }

我的 index.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>
}

这是我的部分观点,在 brek 点我可以看到 51 个结果..

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

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

我通过这个视频一步一步地学会了这一点:视频

试试这个

    <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>
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM