Search code examples
javascriptc#asp.net-corerazor-pages

Updating a partial view with JavaScript in Razor pages


I have a page (Index) which lists all the objects that are inside in a list in the PageModel like so: page with list of objects

Index.cshtml

@page
@model WAD_Website.Pages.Gods.IndexModel
@{
}

<body>
    <label id="lblInformation">Select a God</label>
    <div class="searchGod">
        <form method="post">
            <input type="text" id="txtSearchGod" placeholder="Search for a God..." oninput="SearchGod()" />
        </form>
    </div>
    <div class="godContainer">
        @await Html.PartialAsync("_GodsPartial", Model.GodList);
    </div>
</body>

<script src="~/js/Gods.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

_GodsPartial.cshtml

@using Models.Gods; 
@model List<God>

@foreach (God god in Model)
{
    <a class="god" id="@god.Name" asp-page="/Gods/Builds" asp-route-id="@god.Id">
        <img class="godImage" src="@god.godIcon_URL" />
        <p>@god.Name</p>
    </a>
}

When this index page loads, the list of gods is populated by an API which returns 117 different god objects. I want the user to be able to search this list. When the user enter text in this textbox:

<input type="text" id="txtSearchGod" placeholder="Search for a God..." oninput="SearchGod()" />

it uses Gods.js to call upon a method inside Index.cshtml.cs with jQuery

Gods.js

let txtSearchGod = document.getElementById("txtSearchGod");

function SearchGod() {
    $.ajax({
        type: "POST",
        url: '../../Gods?handler=SearchGod',
        beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
        data: JSON.stringify(txtSearchGod.value),
        contentType: "application/json",
        dataType: "json"
    });
}

Index.cshtml.cs

    public async Task OnGet()
    {
        _godManager = await GodManager.GetInstance();
        GodList = new List<God>();
        God[] gods = _godManager.GetGodList();
        foreach (God god in gods)
        {
            GodList.Add(god);
        }
    }

    public async Task<IActionResult> OnPostSearchGodAsync()
    {
        _godManager = await GodManager.GetInstance();
        GodList = new List<God>();
        God[] gods = _godManager.GetGodList();

        string godName = "";
        {
            MemoryStream stream = new MemoryStream();
            await Request.Body.CopyToAsync(stream);
            stream.Position = 0;
            using (StreamReader reader = new StreamReader(stream))
            {
                string requestBody = await reader.ReadToEndAsync();
                if (requestBody.Length > 0)
                {
                    godName = JsonConvert.DeserializeObject<string>(requestBody);

                    if (godName.Length > 0)
                    {
                        foreach (God god in gods)
                        {
                            if (god.Name.Contains(godName))
                            {
                                GodList.Add(god);
                            }
                        }
                    }
                    else
                    {
                        foreach (God god in gods)
                        {
                            GodList.Add(god);
                        }
                    }
                }
            }
        }
        return Partial("_GodsPartial", GodList);
    }

Everything works fine, as in the list that gets sent to the partial view page does only contain the filtered gods. But I just cannot figure out how to update this piece of HTML.

<div class="godContainer">
    @await Html.PartialAsync("_GodsPartial", Model.GodList);
</div>

I have looked at and tried so many possible solutions, but all to no avail. Can somebody tell me how to update the HTML?


Solution

  • You need to add a success or done handler to your SearchGod function, in which you access the returned HTML and place it in the target element:

    function SearchGod() {
        $.ajax({
            type: "POST",
            url: '../../Gods?handler=SearchGod',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: JSON.stringify(txtSearchGod.value),
            contentType: "application/json",
            dataType: "json"
        }).done(function (response){
            $('.godContainer').html(response);
        });
    }