2

我有_Layout.cshtml,内容是:

...
@RenderSection("MyTitle", required: false)
<div class="innerLR">
    <div id="appContent">
    @RenderBody()
    </div>
</div>
...

当我启动应用程序时,我去这个动作Home/Index,视图

public ActionResult Index()
{
    return View(new BaseModel { Title = "Testing"});
}

视图 Index.cshtml :

@section MyTitle{ @Model.Title }
bla bla bla

这时候没关系,我看到了:Testing + bla bla bla

现在Home/SecondAction,当我单击链接时,我通过 Ajax 调用,控制器返回一个 PartialView 并在appContentdiv 中显示内容。我这样称呼:

$.ajax({
    url: 'Home/SecondAction',
    type: 'POST',
    data: {},
    success: function (result) {
        $(#appContent).html(result);
    }
});

行动是:

public ActionResult SecondAction()
{
    return PartialView(new BaseModel { Title = "Other Title" });
}

SecondAction.cshtml 是:

@section MyTitle{ @Model.Title }
bla bla again

这行不通,我会有任何错误,但我可以从第一个操作中获取文本,而不是:

其他 Titla bla bla 再次

要恢复,我想在返回PartialView渲染部分时从_Layout.cshtml

谢谢,

4

3 回答 3

2

您似乎试图在 AJAX 调用之后更新 DOM 的 2 个不同部分。实现这一目标的一次可能是让您的控制器操作将 2 个部分的呈现结果作为 JSON 返回:

public ActionResult SecondAction()
{
    return Json(new
    {
        section1 = RenderPartialViewToString("_Partial1", null),
        section2 = RenderPartialViewToString("_Partial2", new BaseModel { Title = "Other Title" }),
    });
}

你的 AJAX 调用现在看起来像这样:

$.ajax({
    url: 'Home/SecondAction',
    type: 'POST',
    success: function (result) {
        // TODO: you should of course wrap the contents of section 1 in a div with
        // id="section1" in your _Layout.cshtml
        $('#section1').html(result.section1);

        $('#appContent').html(result.section2);
    }
});

现在您可能想知道RenderPartialViewToString方法来自哪里?它来自here. 或者here如果你愿意的话。

于 2013-04-09T21:22:49.160 回答
0

使用firebug并在控制台中查找错误或 Chrome 网络工具(在 chrome 中按 F12),

它应该是$('#appContent').html(result);

确保你有 IndexPartial View

确保此视图未使用母版页/布局

于 2013-04-09T12:28:30.853 回答
0

我已经深入了解了您SecondAction在 $.ajax 中调用的代码,即:url: 'Home/SecondAction'。但是您的操作方法名称是IndexPartial

public ActionResult IndexPartial()
{
    return PartialView(new BaseModel { Title = "Other Title" });
}

请像这样更改您的 $.ajax 语句:

$.ajax({
    url: 'Home/IndexPartial',
    type: 'POST',
    data: {},
    success: function (result) {
        $(#appContent).html(result);
    }
});

谢谢

于 2013-04-09T12:41:39.387 回答