【问题标题】:MVC view does not update properly after jquery ajax calljQuery ajax 调用后,MVC 视图无法正确更新
【发布时间】:2014-09-08 17:03:18
【问题描述】:

我有一个容器,我从一个返回列表的 PartialView 的 ajax 调用中填充该容器。我有 2 个调用:CreateSplitInput 和 RemoveSplit。

对控制器的调用似乎有效,并且传递给局部视图的模型对于右子列表是正确的。在调试期间,视图似乎会返回正确的 html。

添加新输入我没有问题...删除输入项只会“弹出”列表的最后一项。


更新:MVC 将首先检查 ModelState,然后是 Model。我需要在我的 RemoveSplit 控制器方法中添加 ModelState.Clear()。

感谢awrigley MVC 3 + $.ajax - response seems to be caching output from partial view


TIA!!!

型号:

public class Split
{
    public int SplitID { get; set; }
    public int ClientProfileID { get; set; }
    public int CoveredPersonID { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime? EndDate { get; set; }

    public virtual List<SplitPercent> Percentages { get; set; }
}

public class SplitPercent
{
    public int SplitPercentID { get; set; }
    public int SplitID { get; set; }
    public string PremiumKeyField { get; set; }
    public decimal Percentage { get; set; }
}

控制器:

public ActionResult CreateSplitInput(Split model)
    {
        if (model.Percentages == null)
            model.Percentages = new System.Collections.Generic.List<SplitPercent>();
        model.Percentages.Add(new SplitPercent());
        return PartialView("~/views/clients/_SplitPercentages.cshtml", model);
    }

public ActionResult RemoveSplit(Split model, int index)
    {
        ModelState.Clear(); // <== HERE IS THE ANSWER!!!!!
        if (model.Percentages != null && model.Percentages.Count >= (index + 1))
        {
            model.Percentages.RemoveAt(index);
        }
        return PartialView("~/views/clients/_SplitPercentages.cshtml", model);
    }

Javascrpt:

function addSplit() {
        if (true) { // testing purposes
            $.ajax({
                url: '/clients/CreateSplitInput',
                data: $("#frm").serialize(),
                cache: false,
                success: function(resp) {
                    setSplitContainer(resp);
                },
                error: function(err, status) {
                    alert(status);
                }
            });
        }
    }

function removeSplit(indx) {
        if (true) { // testing purposes
            $.ajax({
                url: '/clients/RemoveSplit/?index=' + indx,
                data: $("#frm").serialize(),
                cache: false,
                type: 'GET',
                success: function(resp) {
                    //debugger;
                    setSplitContainer(resp); //<-- the resp html just has the last item popped off
                },
                error: function(err, status) {
                    alert(status);
                }
            })
        }           
    }

function setSplitContainer(h) {
        $("#splitPercents").html(h);
        $("select").chosen(chosenOpts);
    }

_SplitPercentages.cshtml PartialView:调试此显示正确的百分比集合...似乎正确绑定。

@model BillingWeb.Models.Split


@if (Model != null && Model.Percentages != null)
{
    var logic = new ClientLogic();
    var premiumKeys = logic.GetAllPremiumKeyFields(Model.ClientProfileID);
    string test = "";

    int index = 0;
    foreach (var percent in Model.Percentages)
    {
        test += ", " + percent.PremiumKeyField; // <- collect the model data to show at the end
        var selectList = new SelectList(premiumKeys, percent.PremiumKeyField); // Trying anything now...

        <div class="form-group">
            @Html.Hidden("Percentages.Index", index)
            @Html.Hidden(string.Format("Percentages[{0}].SplitID", index), percent.SplitID)

            <div class="col-md-5 col-lg-5">
                @Html.DropDownListFor(m => m.Percentages[index].PremiumKeyField, selectList, new { @class = "form-control" })
            </div>
            <div class="col-md-4 col-lg-4">
                <div class="input-group">
                    <span class="input-group-addon">%</span>
                    @Html.TextBoxFor(m => m.Percentages[index].Percentage, new { @class = "form-control text-right", placeholder = "Split %" })
                    <button type="button" class="btn btn-danger input-group-addon" onclick="removeSplit(@index)">
                        <span class="glyphicon glyphicon-remove"></span>
                    </button>
                </div>
            </div>
        </div>

        index++;
    }
    <p>@test</p> <!-- WTH?! this works? -->
}

主视图:

@model BillingWeb.Models.Split

    <div class="form-group">
        <label class="control-label col-md-2">Percentages</label>
        <div class="col-md-8">
            <div id="splitPercents">
                @Html.Partial("~/Views/Clients/_SplitPercentages.cshtml", Model)
            </div>
            <button type="button" class="btn btn-primary" onclick="addSplit()">Add Split</button>
        </div>
    </div>

【问题讨论】:

  • splitPercents 函数在哪里?您是否在 splitPercents div 中加载 HTML?
  • splitPercents div 最初是通过@Html.Partial 加载的。用户可以使用 addSplit() 和 removeSplit() 通过 ajax 动态添加/删除输入行。 removeSplit() 调用是问题所在。
  • 您必须将来自服务器的结果附加到 splitPercents div 中。
  • 这就是成功方法在 removeSplit() 函数中所做的。
  • 我误解了你的问题...我更新了帖子以显示 JS 函数 setSplitContainer() 方法。

标签: c# javascript jquery ajax asp.net-mvc


【解决方案1】:

经过更多的挖掘,我发现MVC会先检查ModelState,然后检查Model。

信用:awrigley's response to MVC 3 + $.ajax - response seems to be caching output from partial view

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多