Partial MVC3 Area Update

I am looking for a few pointers when updating partial areas in MVC3 using a razor mechanism.

I am currently using jquery to request ajax.

A small context: I have a list of “Collections”, which I wrapped in a partial view, simply by executing a model object for the view in question for each in the list.

Then I have a “add collection” button, just showing a modal dialog with forms to add a new collection. After clicking add, the ajax request creates a collection in the database and currently returns a JSON object indicating success, as well as the string "Collection Created". In my jjery ajax handler, I check this json object to check if the status is “successful”, and then use jquery to display a reminder that looks like a growl containing the string “Created collection”.

Now my question is: is there anyway I can update my collection list in this ajax request? Is there anyway I can cast a partial view, iterate through the collections, back using the json success object?

Simply put: I wanted to somehow update the HTML, but still support the JSON object, so I can display my notification.

+3
source share
2 answers

You can always make two ajax requests inside the submit handler. Each request would trigger a different controller action (Create, List).

If this does not work for you, have you considered the success message inside the partial?

+1
source

Yes, you can display a partial string and wrap it as JSON. I use this method quite a lot, but I heard people say it badly. So far I have not had any problems, and I have been using it for a couple of years.

ActionResult, JSON. . " " . :

    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();
    }
+1

All Articles