Martin Shishkov
Martin Shishkov

Reputation: 2837

Re-render razor partial view returned from AJAX call

I have the following javascript:

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

this ajax call is receiving a partial view from the controller successfully. The problem is that there is razor syntax in the received partial view which renders correctly on page refresh. Is there a way to re-render only this new chunk of cshtml code without refreshing the whole page?

UPDATE:

This is my view, it is a DisplayTemplate for a comment model:

@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>

And my issue is that the html inside the if statement is not showing right after retrieval - I have to refresh the page in order to render the <a> tag.

Upvotes: 1

Views: 626

Answers (1)

MRebati
MRebati

Reputation: 599

I think your ViewBag.UserId was not set in your PatialView. It's null then the If statement does not execute. that causes the problem.

Upvotes: 2

Related Questions