73

Is there a way to return an HTML string from rendering a partial as part of a JSON response from MVC?

    public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
    {
        if (ModelState.IsValid)
        {
            if(Request.IsAjaxRequest()
                return PartialView("NotEvil", model);
            return View(model)
        }
        if(Request.IsAjaxRequest())
        {
            return Json(new { error=true, message = PartialView("Evil",model)});
        }
        return View(model);
    }
tereško
  • 58,060
  • 25
  • 98
  • 150
Marty Trenouth
  • 3,712
  • 6
  • 34
  • 43

3 Answers3

114

You can extract the html string from the PartialViewResult object, similar to the answer to this thread:

Render a view as a string

PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.

Using the code from the thread above, you would be able to use:

public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
    if (ModelState.IsValid)
    {
        if(Request.IsAjaxRequest())
            return PartialView("NotEvil", model);
        return View(model)
    }
    if(Request.IsAjaxRequest())
    {
        return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
    }
    return View(model);
}
Community
  • 1
  • 1
cacois
  • 2,036
  • 2
  • 19
  • 19
  • if it would be an ajax call calling ReturnSpecialJsonIfInvalid, i believe it is expected to something with data returned. how would jquery differentiate view from json? – mko Sep 15 '14 at 10:22
  • 6
    Where is the definition of RenderViewToString() method? – azhar_SE_nextbridge Jan 28 '17 at 19:01
  • 1
    @Sinjai there is not `RenderViewToString` method with `PartialViewResult` parameter. But there are similar other methods. Inserting the method here would be useful. – Muflix Mar 09 '18 at 16:50
  • how to pass an object of collection, ie ToList() or AsQueryable() object ? – Jun Rikson Aug 31 '18 at 17:57
  • can you write the method RenderViewToString? I need something like this I can not find it. Thanks – Diego Mar 15 '23 at 21:38
35

Instead of RenderViewToString I prefer a approach like

return Json(new { Url = Url.Action("Evil", model) });

then you can catch the result in your javascript and do something like

success: function(data) {
    $.post(data.Url, function(partial) { 
        $('#IdOfDivToUpdate').html(partial);
    });
}
Manatherin
  • 4,169
  • 5
  • 36
  • 52
0
 $(function () {
        $("select#ExamID").change(function (evt) {

            var classid = $('#ClassId').val();
            var StudentId = $('#StudentId').val();
            $.ajax({
                url: "/StudentMarks/ShowStudentSubjects",
                type: 'POST',
                data: { classId: classid, StudentId: StudentId, ExamID: $(this).val() },
                success: function (result) {
                    $('#ShowStudentSubjects').html(result);
                },
                error: function (xhr) { alert("Something seems Wrong"); }
            });
        });
    });
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Jeremy Caney May 15 '22 at 01:50