javascript - 如何在部分 View 中保留 ajax 之后的选择值?

标签 javascript jquery asp.net-core asp.net-core-mvc

在我的 ASP.NET Core Web 应用程序中,我有一个分部 View ,需要将其放置在多个 View 中,并且能够响应动态数据,这些数据将根据当时呈现该分部的 View 而变化。下图中的红色框表示局部渲染的区域。

enter image description here

部分本质上是一个 Select,它将调用存储过程并返回一个数据表并将该表呈现给部分 View 。我能够在页面上选择一个选项并让它调用 SP 并从数据表中查看所有相关数据,并且可以毫无问题地将其写在页面上。我遇到的问题是,每次通过 ajax 刷新部分内容时,Select 都会返回默认的“Select”值,并且不会保留先前选择的选项。

为了简洁起见,假设 FeedbackQueries 对象只包含 4 个字符串元素。

_FeedbackQueryResultPartial.cshtml

@using Contract.Shared;
@model FeedbackQueries


<style>
#select {
    margin: auto;
    text-align: center;
}
</style>

<div id="feedbackQueryResultPartial">
    <div style="height:25px;">
        <div id="select">
            <select name="StoredProcs" id="StoredProcs" onchange="selectQuery()">
                <option value="Select">Select</option>
                @foreach (FeedbackQuery query in Model.Queries)
                {
                    @Html.Raw($"<option value='{query.SprocName}'>{query.SprocName}</option>");
                }
            </select>
        </div>

        <div id="feedbackQueryDiv" class="row">
            @if (Model.FeedbackQueryResults.Rows.Count > 0)
            {
                <h3>DataTable goes here</h3>
            }
            else
            {
                <h3>No rows were returned from your query. Please select another.</h3>
            }
        </div>
    </div>
</div>

Processing.cshtml

@using Contract.Parent
@using Contract.Shared
@model Processing
<script>
        function showFeedbackPartial(x, y, z, q) {
            $.ajax({
                cache: false,
                url: '@Url.Action("GetFeedbackQueryDatatable", "Client")',
                type: 'POST',
                data: { databaseConnectionString: x, storedProcedure: y, page: z, Model: q },
                success: function (result) {
                    var selected = $('#StoredProcs').val();
                    console.log(selected);
                    if (result.rowCount > 0) {
                        console.log(result.rowCount);
                        var databaseConnectionString = x;
                        var storedProcedure = y;
                        var page = z;
                        var model = q;
                        var url = '@Url.Action("ViewFeedbackQueryPartial", "Client")';
                        $("#feedbackQueryResultPartial").load(url, { databaseConnectionString, storedProcedure, page, model });
                    }
                    else {
                        document.getElementById('feedbackQueryDiv').innerHTML = '<h3>No rows were returned from your query.  Please select another.</h3>';
                    }
                    $('#StoredProcs').val(selected);
                    $("#StoredProcs option[value='Select']").remove();
                }
            });
        }
    </script>
    <script>
        function selectQuery() {
            var e = document.getElementById('StoredProcs');
            var ev = e.options[e.selectedIndex].text;
            var p = 'Processing';
            var model = @Html.Raw(Json.Serialize(Model.FeedbackQueries));
            console.log(model);
            showFeedbackPartial('@Model.Client.DatabaseConnectionString', ev, p, model);

        }
    </script>
    <script>
        $(document).ready(function () {
            document.getElementById('feedbackQueryDiv').innerHTML = '<h3>Select a query to view feedback.</h3>';
        });
    </script>
}
<form method="post" enctype="multipart/form-data">
...
    <partial name="_FeedbackQueryResultPartial" for="@Model.FeedbackQueries" />
...
</form>

呈现处理 View 的 Controller 操作

[HttpGet]
        public IActionResult Processing(int Id)
        {
            ViewBag.Id = Id;
            Processing processing = new Processing();

            //Get pertinent information for Client 
            processing.Client = _clientProcessingService.GetSingleClient(Id, _appSettings.MOPConfigConnectionString);
            processing.Client.DatabaseConnectionString = _clientProcessingService.GetClientConnectionFromConfig(processing.Client, _appSettings);
            processing.Steps = _clientProcessingService.GetClientSteps(processing.Client.DatabaseConnectionString, "Processing");
            processing.CurrMoInfo.CurrMo = _clientProcessingService.GetProcessingCurrMo(processing.Client.DatabaseConnectionString);
            processing.FeedbackQueries = _clientProcessingService.GetFeedbackQueriesFromDb(processing.Client.DatabaseConnectionString, "Processing");

            return View(processing);
        }

        [HttpPost]
        public IActionResult Processing(Processing Model)
        {
            //Get pertinent information for Client 
            Model.Client = _clientProcessingService.GetSingleClient(Model.Client.ClientID, _appSettings.MOPConfigConnectionString);
            Model.Client.DatabaseConnectionString = _clientProcessingService.GetClientConnectionFromConfig(Model.Client, _appSettings);
            Model.Steps = _clientProcessingService.GetClientSteps(Model.Client.DatabaseConnectionString, "Processing");
            Model.CurrMoInfo.CurrMo = _clientProcessingService.GetProcessingCurrMo(Model.Client.DatabaseConnectionString);
            Model.FeedbackQueries = _clientProcessingService.GetFeedbackQueriesFromDb(Model.Client.DatabaseConnectionString, "Processing");

            return View(Model);
        }

呈现局部的 Controller Action

public IActionResult ViewFeedbackQueryPartial(string DatabaseConnectionString, string StoredProcedure, string Page, FeedbackQueries Model)
{
    if(StoredProcedure == "Select")
    {
        return PartialView("_FeedbackQueryResultPartial", Model);
    }
    Model.FeedbackQueryResults = _clientProcessingService.GetFeedbackQueryDataTable(DatabaseConnectionString, Page, StoredProcedure);

    return PartialView("_FeedbackQueryResultPartial", Model);
}

我尝试了很多不同的方法来保持这个值(value)。将其添加到模型、将其添加到 Viewbag 以及无数其他尝试在某处保留此值的方法,无论成功或失败,都保留该值并通过 javascript 将其更改为选定的选项。每次调用 ajax 后重新加载部分时,它都会重置为“选择”。

这也带来了另一个问题,当我通过单击 RUNProcessing View 上提交表单时,页面将刷新并转到过程中的下一步,但是理想情况下还应该发生的是保留部分中的值,再次运行查询并且用户不需要在任何时候选择新值,除非他们想运行不同的 SP 以查看表中的不同数据.

这是可能的还是我试图以完全错误的方式做到这一点?

最佳答案

对于您的问题,您可能需要将选定的 SprocName 从父 View 传递到带有 Model 的部分 View 。

  1. SelectedSprocName 添加到 FeedbackQueries

    public class FeedbackQueries
    {
        public string SelectedSprocName { get; set; }
        public List<FeedbackQuery> Queries { get; set; }
        public FeedbackQueryResults FeedbackQueryResults { get; set; }
    }
    
  2. 更改 View 以设置SelectedSprocName

    function showFeedbackPartial(x, y, z, q) {
        $.ajax({
            cache: false,
            url: '@Url.Action("GetFeedbackQueryDatatable", "Process")',
            type: 'POST',
            success: function (result) {
                var selected = $('#StoredProcs').val();                   
                model.SelectedSprocName = selected;
                var url = '@Url.Action("ViewFeedbackQueryPartial", "Process")';
                $("#feedbackQueryResultPartial").load(url,{ databaseConnectionString, storedProcedure, page, model });
                console.log('after load' + selected);
               // your rest code
            }
        });
    }
    
  3. 部分 View 设置选定选项

    @foreach (FeedbackQuery query in Model.Queries)
    {
        if (query.SprocName == Model.SelectedSprocName)
        {
            @Html.Raw($"<option value='{query.SprocName}' selected='true'>{query.SprocName}</option>");
        }
        else
        {
            @Html.Raw($"<option value='{query.SprocName}'>{query.SprocName}</option>");
        }
    }
    

关于javascript - 如何在部分 View 中保留 ajax 之后的选择值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58084674/

相关文章:

javascript - 如果单词后最后删除的字母是空格,则阻止 if 语句

c# - 无法从 appsettings.json 读取数据

javascript - 如何将 anchor href 属性添加到选项对象?

javascript - 如何过滤多个元素/元素

javascript - 如何从使用 api 返回的 JSON 对象初始化 google.maps.DirectionsResult?

javascript - 使用 React 监听整个 dom 上的点击事件的正确方法是什么?

javascript - JQuery 未加载到 Chrome 扩展内容脚本中

javascript - 使用html :not when element has multiple classes

c# - 使用 .NET 核心中的 dapper 批量插入 PostgreSQL

c# - 依赖注入(inject)循环依赖.NET Core 2.0