szpic
szpic

Reputation: 4496

Render View html to string

I'm trying to get generated html of a View and load it into the modal window.

Controller receives correct ID. And returns View. I assume ajax does not recognize return data as a correct response and throw error.

Can anyone suggest me modifications to the code that allows me to get html code of a view?

Here my Ajax code:

$(document).ready(function () {
$('.details-btn').on('click', function () {
    $.ajax({
        url: "/Device/Details",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        data: JSON.stringify({ id: $(this).attr('id') }),
        error: function (data) {
            alert("wystąpił nieokreślony błąd " + data);
        },
        success: function (data) {
            console.log(data);
            $('.modal-body').append(data);
            $("#DetailsModal").modal('show');
        }
    });
});

});

and controller method I'm calling

public Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Device device = unitOfWork.deviceRepository.GetByID(id.Value);
        if (device == null)
        {
            return HttpNotFound();
        }
        return View(device);
    }

Upvotes: 0

Views: 154

Answers (1)

HCJ
HCJ

Reputation: 527

Try to remove JSON.stringify for the data property in ajax call

Also change dataType (type of data return from controller) property to "html.

data: {'id', $(this).attr('id')},
datatype: "html",

Upvotes: 2

Related Questions