I'm rendering a page where part of the page is a FORM -- rendered via a partial. The submit button on that form posts to my controller via Ajax (using JQuery .post()). When the controller action takes over there are two possible execution paths:
The form data is valid. In this case the controller updates the database with a new record and then returns an HTML table by rendering a PartialView (and returns a ViewResult).
The form data is invalid. In this case I want to re-render the original form -- with the validation failures highlighted. I believe I can do this with a different PartialView invocation.
On the client side, in the completion javascript function, I have to differentiate between the success and failure cases because the DOM target for the returned HTML will be different. I guess I could inspect the HTML for some known element to differentiate the cases, but it seemed to me that a better solution would be to return a JSonResult that contains a boolean status in one field and the HTML in another.
I know how to return a JsonResult from the controller. However, I need to be able to capture the HTML from the PartialView calls in order to stick that text into the field. Does anyone know:
(a) how to do this, and/or
(b) a better way to approach the situation.
TIA
Update 8/20/2009
I think I am coming close to what I want with this code:
ViewEngineResult viewEngineResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, "HospitalDoseList");
ViewData.Model = hospitalStay;
ViewContext viewContext = new ViewContext(ControllerContext, viewEngineResult.View, this.ViewData, this.TempData);
using (StringWriter writer = new StringWriter()) {
viewEngineResult.View.Render(viewContext, writer);
string html = writer.ToString();
JsonResult jsonResult = new JsonResult();
jsonResult.Data = new {Status = true, Html = HttpUtility.HtmlEncode(html)};
return jsonResult;
}
However, the html string is coming up blank where I expected it to contain the HTML that would normally be rendered to the response stream via a call to
return PartialView("HospitalDoseList", hospitalStay);