【问题标题】:Re-render razor partial view returned from AJAX call重新渲染从 AJAX 调用返回的剃刀局部视图
【发布时间】:2015-07-19 19:40:00
【问题描述】:

我有以下 javascript:

            $.ajax({
                type: "POST",
                url: url,
                data: $(form).serialize(),
                success: function (res) {
                    commentsField.append(res);
                }
            });

此 ajax 调用正在成功地从控制器接收部分视图。问题是接收到的局部视图中有剃刀语法,它在页面刷新时正确呈现。有没有办法只重新渲染这段新的 cshtml 代码而不刷新整个页面?

更新:

这是我的观点,它是一个评论模型的 DisplayTemplate:

@model CommentModel

<div class="comment">
@Model.Body &#8212; <span class="buttonlink">@Model.AuthorUsername</span>; @Model.PostDate.ToString("F", CultureInfo.CreateSpecificCulture("bg-BG"))
    @if (ViewBag.UserId != null && ViewBag.UserId.Equals(Model.AuthorId))
    {
        <a class="comment-delete-btn" href="javascript:{}" data-parentid="@Model.ParentId" data-id="@Model.Id"><span class="fa fa-times-circle pull-right"></span></a>
    }
</div>

我的问题是 if 语句中的 html 在检索后没有立即显示 - 我必须刷新页面才能呈现 &lt;a&gt; 标记。

【问题讨论】:

  • 你能分享你的部分视图代码和渲染的html吗?
  • 我怀疑您的ViewBag.UserIdnull,因为您拨打了ajax,并且可能没有在POST 操作中设置ViewBag.UserId 值。您在 get 中设置的 ViewBag.UserId 不会影响您的 post 操作。这可能就是为什么您只有在刷新后才能正常看到它的原因。
  • 谢谢,问题解决了!如果您愿意,可以将此作为答案发布,以便我接受:)

标签: javascript ajax asp.net-mvc razor


【解决方案1】:

我认为您的 ViewBag.UserId 未在您的 PatialView 中设置。如果为空,则不执行 If 语句。这会导致问题。

【讨论】:

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