I'm looking for a few pointers in updating partial areas in MVC3 with razor engine.
Right now, I'm using jquery for the ajax request.
A little context: I have a list of "Collections" which I wrapped in a partial view, just performing a for-each on a list in the model object of the view in question.
I then have a "add collection" button, with just shows a modal dialog box with the forms for adding a new collection. Upon clicking "add" an ajax request creates the collection in the database, and currently returns a JSON object indicating a success along with the string "Collection Created". In my jquery ajax handler, I examine this json object, to check if the status is "success" and then use jquery to display a growl-like notification containt the "Collection Created" string.
Now my question is: Is there anyway I can update my list of collection in this ajax request? Is there anyway I can throw the partial view, iterating the collections, back with the success json object somehow?
Put very simply: I'd like to update HTML somehow, but still maintain the JSON object, so I can display my notification.
You can always make two ajax requests inside a submit handler. Each request would call a different controller action (Create, List).
If that doesn't work for you, have you considered displaying success message inside a partial?
Yes, you can render your partial as a string and wrap it up as JSON. I use this method quite a lot but I've heard people saying it's bad practice. So far I haven't experienced any problems and I've been using it for a couple of years.
I actually use a custom ActionResult which returns JSON. It wraps up multiple views and sends them back to the client as an Array of strings. The "not so straight forward" bit is rendering views as strings from within a controller action. Here's some code to do that:
public static string RenderViewToString(ControllerContext controllerContext, string viewPath, ViewDataDictionary viewData, TempDataDictionary tempData)
{
ViewEngineResult result = ViewEngines.Engines.FindPartialView(controllerContext, viewPath);
if (result == null || result.View == null)
throw new Exception("No view found for the following path: " + viewPath);
ViewContext viewContext = new ViewContext(controllerContext, result.View, viewData, tempData, new StringWriter());
HtmlHelper helper = new HtmlHelper(viewContext, new ViewPage());
return helper.Partial(viewPath, viewData).ToHtmlString();
}