MVC Return Partial View as JSON

Ajaxasp.net MvcValidation

Ajax Problem Overview


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);
    }

Ajax Solutions


Solution 1 - Ajax

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

https://stackoverflow.com/questions/483091/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);
}

Solution 2 - Ajax

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);
    });
}

Solution 3 - Ajax

 $(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"); }
            });
        });
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarty TrenouthView Question on Stackoverflow
Solution 1 - AjaxcacoisView Answer on Stackoverflow
Solution 2 - AjaxManatherinView Answer on Stackoverflow
Solution 3 - AjaxNirpat ChaudharyView Answer on Stackoverflow