简体   繁体   中英

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

I have a search text box and a button. I want to show the results of the search in a partial view with ajax when the button is clicked. When I set a break point in the partial view I can see data but nothing shows on the form.

My controller that passes the text value for the search:

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

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

            return PartialView("_SearchResults");
        }

My index.cshtml view code:

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

and this is my partial view that in brek point I can see 51 number of results ..

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

I don't have an error in compile and run time, and no error in the browser ...

I learned this step by step with this video: video

Try This One

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

resultsDiv will update after complete ajax call

Also make sure your foreach loop data

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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