问题出现在加载时调用的jQuery (MVC)。

huangapple go评论61阅读模式
英文:

Issue with jquery on load call (MVC)

问题

以下是代码的翻译部分:

我有一个部分视图,我称之为GetPayeeList,它只是显示一个Payee类的下拉列表。以下是视图的代码:

<div class="form-floating mb-3 full-width">
    @Html.DropDownListFor(model => model.PayeeId,
                        new SelectList(Model.Payees, "Id", "Name"), "Select Payee", new { @class = "form-control full-width" })
    @Html.LabelFor(model => model.PayeeId, htmlAttributes: new { @class = "control-label" })
    @Html.ValidationMessageFor(model => model.PayeeId, "", new { @class = "text-danger" })
</div>

以下是与之相关的Action方法的代码:

[HttpGet]
public ActionResult GetPayeeList(int pid)
{
    List<Payee> allPayees = _dbContext.Payee.Where(p => p.Name != null && p.Name != "").OrderBy(p => p.Name).ToList();
    
    PayeeDDViewModel viewModel = new PayeeDDViewModel()
    {
        Payees = allPayees,
        PayeeId = pid,
    };
    
    return View(viewModel);
}

现在,我有一个视图,显示这个下拉列表,并允许使用jquery调用刷新列表(因为用户可以使用链接添加一个payee到列表,这意味着当前列表已过时)。这个视图被称为_PayoutDetails,以下是相关部分的代码:

<div class="form-floating mb-3 col-4 full-width">
    <div id="PayeeRefreshDiv" class="clickable-div">
        刷新列表 <span style="font-size:larger;">↻</span>
    </div>
    <div id="PayeeListDiv" class="row">
         @Html.Action("GetPayeeList", "Home", new { pid = Model.PayeeId })
    </div>
    @Html.ActionLink("Add a Payee", "PayeeDetails", new { id = 0 }, new { target = "_blank" })
</div>

在Script部分,我有以下部分:

$(':input').change(function() {
    var fieldName = $(this).attr('name');
    var fieldValue = $(this).val();
    var payoutId = @Model.Id;

    $.ajax({
        type: 'POST',
        url: '/home/ChangePayoutDetailInput',
        data: {
            input: fieldName,
            value: fieldValue,
            pid: payoutId
        },
        dataType: 'json',
        success: function(data) {
            //alert('success');
            console.log(data);
            var SuccessDiv = $('#successStatusDiv');
            SuccessDiv.show(1000);
            setTimeout(function() {
                SuccessDiv.hide();
            }, 3000);
        },
        error: function() {
            console.log('An error occurred while making the request.');
        }
    });
});

$('#PayeeRefreshDiv').on("click", function() {
    reloadPayee($('#PayeeId').val());
});

function reloadPayee(pid) {
    $('#PayeeListDiv').load('@Url.Action("GetPayeeList", "Home")' + "?pid=" + pid);
};

当下拉选择发生变化时,我调用Action方法:ChangePayoutDetailInput,并发送参数。一切都很顺利,直到用户点击刷新链接,调用jquery中的reloadPayee函数,并使用先前复制的Action方法重新加载下拉列表。尽管加载工作正常,下拉框被新的数据库条目填充(如果用户添加了新的payee等),但似乎$(':input').change(function () {... 不再触发,原因不明。我甚至尝试欺骗并将整个$(':input').change(function () {... 块添加到reloadPayee函数中,但没有成功。

您有没有想法,为什么一旦刷新div,下拉框的change函数就停止被调用,以及如何使其正常工作?

英文:

I have a partial view I call GetPayeeList that simply displays a dropdown list of Payee class. Here's the code for the view:

@model DocuVerse.ViewModels.PayeeDDViewModel
    
@{
    Layout = null;
}
    
&lt;div class=&quot;form-floating mb-3 full-width&quot;&gt;
    @Html.DropDownListFor(model =&gt; model.PayeeId,
                        new SelectList(Model.Payees, &quot;Id&quot;, &quot;Name&quot;), &quot;Select Payee&quot;, new { @class = &quot;form-control full-width&quot; })
    @Html.LabelFor(model =&gt; model.PayeeId, htmlAttributes: new { @class = &quot;control-label&quot; })
    @Html.ValidationMessageFor(model =&gt; model.PayeeId, &quot;&quot;, new { @class = &quot;text-danger&quot; })
&lt;/div&gt;

And here's the Action method's code behind it:

[HttpGet]
public ActionResult GetPayeeList(int pid)
{
    List&lt;Payee&gt; allPayees = _dbContext.Payee.Where(p =&gt; p.Name != null &amp;&amp; p.Name != &quot;&quot;).OrderBy(p =&gt; p.Name).ToList();
    
    PayeeDDViewModel viewModel = new PayeeDDViewModel()
    {
        Payees = allPayees,
        PayeeId = pid,
    };
    
    return View(viewModel);
}

Now, I have a view that displays this dropdown and allows for the list to be refreshed using jquery call (since the user can add a payee to the list using a link which would mean the current list is out of date). This view is called _PayoutDetails and here's partial code for the relevant sections:

&lt;div class=&quot;form-floating mb-3 col-4 full-width&quot;&gt;
    &lt;div id=&quot;PayeeRefreshDiv&quot; class=&quot;clickable-div&quot;&gt;
                    Refresh List &lt;span style=&quot;font-size:larger;&quot;&gt;↻&lt;/span&gt;
    &lt;/div&gt;
    &lt;div id=&quot;PayeeListDiv&quot; class=&quot;row&quot;&gt;
         @Html.Action(&quot;GetPayeeList&quot;, &quot;Home&quot;, new { pid = Model.PayeeId })
    &lt;/div&gt;
    @Html.ActionLink(&quot;Add a Payee&quot;, &quot;PayeeDetails&quot;, new { id = 0 }, new { target = &quot;_blank&quot; })
&lt;/div&gt;

and in the Script section, I have (partially):

$(&#39;:input&#39;).change(function() {
    var fieldName = $(this).attr(&#39;name&#39;);
    var fieldValue = $(this).val();
    var payoutId = @Model.Id;

    $.ajax({
        type: &#39;POST&#39;,
        url: &#39;/home/ChangePayoutDetailInput&#39;,
        data: {
            input: fieldName,
            value: fieldValue,
            pid: payoutId
        },
        dataType: &#39;json&#39;,
        success: function(data) {
            //alert(&#39;success&#39;);
            console.log(data);
            var SuccessDiv = $(&#39;#successStatusDiv&#39;);
            SuccessDiv.show(1000);
            setTimeout(function() {
                SuccessDiv.hide();
            }, 3000);
        },
        error: function() {
            console.log(&#39;An error occurred while making the request.&#39;);
        }
    });
});

$(&#39;#PayeeRefreshDiv&#39;).on(&quot;click&quot;, function() {
    reloadPayee($(&#39;#PayeeId&#39;).val());
});

function reloadPayee(pid) {
    $(&#39;#PayeeListDiv&#39;).load(&#39;@Url.Action(&quot;GetPayeeList&quot;, &quot;Home&quot;)&#39; + &quot;?pid=&quot; + pid);
};

So when the dropdown selection changes, I call the action method: ChangePayoutDetailInput and send parameters. Everything works well and fine until the user clicks on the refresh link which calls the reloadPayee function in jquery and reloads the dropdown using the previously copied action method. Even though the load works and the dropdown gets populated with the new db entries (if the user added a new payee, etc.) but the $(&#39;:input&#39;).change(function () { doesnt seem to get triggered again for whatever reason. I even tried cheating and adding the whole block of $(&#39;:input&#39;).change(function () {... to the reloadPayee function with no success.

Any idea why as soon as the div is refreshed the dropdown's change function stops getting called and how to get it to work?

答案1

得分: 2

当你替换整个#PayeeListDiv内容时,你必须重新添加你提到的change监听器。但是似乎你将它放在了reloadPayee()函数中,而不是$().load()回调中。请尝试这样做:

function reloadPayee(pid) {
    $('#PayeeListDiv').load(
        '@Url.Action("GetPayeeList", "Home")' + "?pid=" + pid,
        function( response, status, xhr ) {
             // 在这里重新添加监听器
             $(':input').change(function () {...});
        }
    );
};
英文:

As you substitute entire #PayeeListDiv content you have to re-add your change listener as you mentioned. But seems you have put it into reloadPayee() function rather than $().load() callback. Please try this

function reloadPayee(pid) {
    $(&#39;#PayeeListDiv&#39;).load(
        &#39;@Url.Action(&quot;GetPayeeList&quot;, &quot;Home&quot;)&#39; + &quot;?pid=&quot; + pid,
        function( response, status, xhr ) {
             // re-add listener here
             $(&#39;:input&#39;).change(function () {...});
        }
    );
};

</details>



huangapple
  • 本文由 发表于 2023年6月19日 03:48:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76502289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定