如何在与 PartialView A 交互时切换到 PartialView A 到 PartialView B?

How to switch to PartialView A to PartialView B on interaction with PartialView A?

有一个 ParentPage 在右窗格中显示 PartialViewAPartialViewA 内有一个下拉菜单。在选择某个值时,我想用 PartialViewB 替换 PartialViewA。这可能吗?我该怎么做?

我试过了: (PartialViewA:)

<script>
    $(document).ready(function () {
        alert('aa');
        $("#drpisEmpty").change(function () {
            if ($(this).val() == "loaded") {
                alert($(this).val());
            }
            else {              
                window.location.href = '@Url.Action("PartialViewB", "ParentController", new { CargoType = "PartialViewA" })';

            }
        });
    });
</script>

CallCargoTypePartialView:(ParentController)

  public ActionResult CallCargoTypePartialView(string CargoType)
        {
            if (CargoType == "PartialViewA")
            {
                return View("_PartialViewA");
            }
            else if (CargoType == "PartialViewB")
            {
                return View("_PartialViewB");
            }
            return View("_PartialViewA");
        }

我面临的问题是,当我从 PartialViewB 或副 verce 中调用 PartialViewA 时,整个页面(连同父页面)被 PartialView 的输出替换。

问题出现在这一行:

window.location.href = '@Url.Action("PartialViewB", "ParentController", new { CargoType = "PartialViewA" })';

通过使用 location.href,您将用来自控制器操作的 returned 页面替换现有页面的整个元素,因此现有视图将被新视图覆盖。

假设您有此设置:

<div id="partial">
    @Html.Partial("_PartialViewA")
</div>

然后你需要在 else 块内执行 AJAX 回调并将其附加到 success 由先前局部视图的占位符标记的结果,如下例所示:

<script>
    $(document).ready(function () {
        alert('aa');
        $("#drpisEmpty").change(function () {
            if ($(this).val() == "loaded") {
                alert($(this).val());
            }
            else {              
                $.ajax({
                    type: 'GET',
                    url: '@Url.Action("CallCargoTypePartialView", "ParentController")',
                    data: { CargoType: "PartialViewB" }, // example passed data
                    success: function (result) {
                        // replace first partial view with the second one
                        $('#target').html(result);
                    },
                    error: function (...) {
                        // error handling
                    }
                });

            }
        });
    });
</script>

另请注意,您应该 return PartialView() 而不是 View():

public ActionResult CallCargoTypePartialView(string CargoType)
{
   if (CargoType == "PartialViewA")
   {
       return PartialView("_PartialViewA");
   }
   else if (CargoType == "PartialViewB")
   {
       return PartialView("_PartialViewB");
   }
   return PartialView("_PartialViewA");
}