ajax - 部分 View 也返回共享布局页面

标签 ajax asp.net-mvc asp.net-mvc-3 jquery partial-views

在我的 ASP MVC3 View 中,我使用以下 Ajax 调用来检索部分 View 并将部分 View 附加到特定的字段集

Ajax

    $("#addItem").click(function () {
        alert("here");
        $.ajax({
            url: '@Url.Action("BlankDropDownItem", "DropDownValues")',
            dataType: 'html',
            cache: false,
            success: function (html) {
                alert(html);
                $("#items").append(html); 
            }
        });
        return false;
    });

此 Ajax 调用一个非常简单的 ViewResult Controller 方法,该方法应该返回部分 View 。

Controller

    public ViewResult BlankDropDownItem()
    {
        return View("DropDownItemPartial", new DropDownValues());
    }

这是部分中的所有代码。当我在 VS 2010 中创建它时(我已经这样做了两次只是为了确保)我选中了“部分 View ”复选框,该复选框使“使用共享布局”选项变灰。

部分 View

@model Monet.Models.DropDownValues
<div class="editor-label">
     @Html.LabelFor(model => model.AllowedValue)
</div>
<div class="label-field">
    @Html.EditorFor(model => model.AllowedValue)
    @Html.ValidationMessageFor(model => model.AllowedValue)
</div>
<div class="editor-label">
    @Html.LabelFor(model => model.DisplayValue)
</div>
<div class="label-field">
    @Html.EditorFor(model => model.DisplayValue)
    @Html.ValidationMessageFor(model => model.DisplayValue)
</div>

无论出于什么原因,当我在 Ajax success 函数的这一行返回的 html 对象上放置 alert

success: function (html) {

我看到 html 对象返回共享布局中的所有 HTML,因此它本质上返回整个页面而不是部分 View 。下面是 Ajax 调用完成后的屏幕截图。

enter image description here

最佳答案

我认为您遇到了一个“容易错过”的小语法问题:D

你有:

public ActionResult BlankDropDownItem()
{
    return View("DropDownItemPartial", new DropDownValues());
}

您应该:

public ActionResult BlankDropDownItem()
{
    return PartialView("DropDownItemPartial", new DropDownValues());
}

希望这有帮助!

关于ajax - 部分 View 也返回共享布局页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16721727/

相关文章:

c# - ASP.NET Identity中UserStore和UserManager的使用有什么区别?

.net - EF Fluent API 教程

Asp.NET MVC 路由性能

javascript - Yii2 - 将 ID 传递给 GridView 中的另一个属性

c# - 向 100K 用户添加 cookie 时要考虑的性能问题?

jquery - 如果是Ajax,则在参数中发送特殊字符

c# - 通过 GET 请求将 JSON 参数传递给 MVC Controller

c# - 如何使用表单例份验证在 MVC 中实现新用户电子邮件验证

php - 来自 PHP 结果的 jQuery json

jquery - jQuery 有自己的 Ajax 支持吗?