Jon
Jon

Reputation: 40032

Return PartialView and Javascript from Controller

I see there is a question here but there is no definite answer. Has anyone any ideas how to return a PartialView with Javascript or JSON. I am doing an AJAX post, on success it renders the PartialView but then needs to run some javascript or check the JSON result.

Upvotes: 1

Views: 863

Answers (2)

Jon
Jon

Reputation: 40032

public static string RenderPartialToString(string controlName, object viewData, object model, System.Web.Routing.RequestContext viewContext)
            {

                ViewDataDictionary vd = new ViewDataDictionary(viewData);
                ViewPage vp = new ViewPage { ViewData = vd };

                vp.ViewData = vd;
                vp.ViewData.Model = model;
                vp.ViewContext = new ViewContext();
                vp.Url = new UrlHelper(viewContext);

                Control control = vp.LoadControl(controlName);

                vp.Controls.Add(control);

                StringBuilder sb = new StringBuilder();

                using (StringWriter sw = new StringWriter(sb))
                {

                    using (HtmlTextWriter tw = new HtmlTextWriter(sw))
                    {

                        vp.RenderControl(tw);

                    }

                }

                return sb.ToString();

            }

Upvotes: 1

Ronald Wildenberg
Ronald Wildenberg

Reputation: 32104

I think the answer provided for the other question may be your best option. You can not suddenly have another onSuccess method signature where another parameter is added with a JSON object, so you are stuck with one return object. Logically, this object then must contain both your view and your JSON object, which implies that the object itself must be a JSON object.

Upvotes: 0

Related Questions