kat1330
kat1330

Reputation: 5322

Render partial view with JQuery / AJAX

I try to render partial view and place between div elements. I read few articles e.g. Rendering a partial view with jquery but still doesn't work.

Where I made mistake?

A.) Place where I want to render my partial view:

<div id="target">

        </div>

If I put between and @Html.Partial() I received error!

B.) How I call controler action:

 $("#target").load('@Url.Action("GetMessageTypeView", "EmailMessages")');

I also tried with:

$.ajax({
        url: '@Url.Action("GetMessageTypeView", "EmailMessages")',
        type: "POST",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        $('#target').html(data);
    }
});

In both cases I called controller action, but no result.

C.) My controller action:

public ActionResult GetMessageTypeView()
    {
        return PartialView("Partials/MessageTypes");
    }

Where I made mistake? Is it possible to render partial view and put somewhere in the page without call controler? Thanks

Upvotes: 0

Views: 4977

Answers (1)

user1618236
user1618236

Reputation:

Without seeing the error you mentioned I do see one issue with your code, the content type on your ajax call is incorrect it should be:

$.ajax({
        url: '@Url.Action("GetMessageTypeView", "EmailMessages")',
        type: "POST",
    contentType: "text/html; charset=utf-8",
    success: function (data) {
        $('#target').html(data);
    }
});

jquery is expecting json to be returned from the server but when it gets the html of the partial view it doesn't know what to do with it. I've had this problem recently and I didn't even get an error, it just didn't do anything.

Upvotes: 3

Related Questions