调用部分视图后,主视图堆叠在同一页面上

时间:2017-07-07 09:12:51

标签: javascript jquery ajax asp.net-mvc

我有这个动作,根据下拉列表中的选定值返回不同的局部视图。

控制器:

[HttpPost]
        public ActionResult Foo(SomeViewModel VM)
        {
            var model = VM
            if (Request.IsAjaxRequest())
            {
                if (model.SelectedValue == 1 || model.SelectedValue == 2 || model.SelectedValue == 3)
                {
                    // ...
                    return PartialView("PartialView1", model);
                }
                else if (model.SelectedValue == 4)
                {
                    // ...
                    return PartialView("PartialView2", model);
                }
                else (model.SelectedValue == 5)
                {
                    // ...
                    return PartialView("PartialView3", model);
                }
            }
            return View(model);
        }

主要观点:

<script src="~/Scripts/jquery-3.2.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<div>
    <h2>Paint Computation</h2>
    @using (Ajax.BeginForm("Foo", "Controller",
 new AjaxOptions
 {
     HttpMethod = "POST",
     UpdateTargetId = "Result"
 }))
    {
        <div class="col-md-10">
            <h5>Type of Paint</h5>
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.DropDownListFor(m => m.SelectedValue, new SelectList(Model.PaintType, "Value", "Text"),
                "Please Select", htmlAttributes: new { @class = "form-control" })
            </div>
            <br />

        // Some HTML helpers
            <input type="submit" value="Compute" class="btn btn-default" id="Submit" />

        </div>
    }
</div>

//This is how I render my partial view using jQuery in my main View:

    <div id="Result">
        <hr />
    </div>

    <script type="text/javascript">
        $(document).ready(function () {
            $('#Submit').click(function () {
                $('#Result').load('/Controller/Foo');
            });
        });
    </script>

每当我点击按钮时,都会显示局部视图,但是当我第三次或第四次再次点击它时,主视图内容会堆叠在同一主视图上。我试图使用inspect元素,这就是我如何确定它堆叠相同的主视图元素。

我调用局部视图的方式是对的吗?我希望每次单击按钮时都使用ajax调用局部视图。请指导我纠正它。谢谢。

这是问题的screenshot

1 个答案:

答案 0 :(得分:0)

<script type="text/javascript">
    $(document).ready(function () {
        $('#Submit').click(function () {
            $.ajax({
                type: 'POST',
                url: '/Controller/Foo',
                cache: false,
                contentType: "application/html; charset=utf-8",
                dataType: 'html',
                success: function (result) {
                    $('#Result').html(result);
                }
            });
        });
    });
</script>

现在它有效。我更改了代码并使用上面的代码。我使用.html()而不是.append()或.replaceWith()。现在每次我点击按钮,它都会改变<div id = "Result> content.