I would really not recommend this approach - if you want to make sure the call was a success, use the HTTPHeader that is built-in in the protocol and in the jQuery library. If you take a look at the API documentation for $.ajax
you'll se that you can have different reactions to different HTTP status codes - there are, for example, success and error callbacks.
With that approach, your code would look something like
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: $(this).serialize(),
dataType: 'HTML',
success: function(data, textStatus, XMLHttpRequest) {
alert(textStatus);
$('#test').html(data);
},
error: function(XmlHttpRequest, textStatus, errorThrown) {
// Do whatever error handling you want here.
// If you don't want any, the error parameter
//(and all others) are optional
}
}
And the action method simply returns the PartialView
:
public ActionResult ThisOrThat()
{
return PartialView("ThisOrThat");
}
But yes, it can be done your way too. The problem with your approach is that you're returning the PartialView
itself, rather than the output HTML. Your code would work if you changed it to this:
public ActionResult HelpSO()
{
// Get the IView of the PartialView object.
var view = PartialView("ThisOrThat").View;
// Initialize a StringWriter for rendering the output.
var writer = new StringWriter();
// Do the actual rendering.
view.Render(ControllerContext.ParentActionViewContext, writer);
// The output is now rendered to the StringWriter, and we can access it
// as a normal string object via writer.ToString().
// Note that I'm using the method Json(), rather than new JsonResult().
// I'm not sure it matters (they should do the same thing) but it's the
// recommended way to return Json.
return Json(new { success = true, Data = writer.ToString() });
}