代码之家  ›  专栏  ›  技术社区  ›  Jaco Pretorius

MVC Ajax-解析表单提交返回数据

  •  1
  • Jaco Pretorius  · 技术社区  · 16 年前

    我正在使用MVC Ajax进行表单提交。我无法正确处理的是让服务器上的Action向浏览器返回部分视图。

    <% using (Ajax.BeginForm("Add", "Example", new AjaxOptions { HttpMethod = FormMethod.Post.ToString(), OnComplete = "widgetAdded" } )) { %>
    

    function widgetAdded(ajaxContext) {
        var response = ajaxContext.get_response().get_object();
        alert(response);
    }
    

    return Json("bob");
    

    return PartialView("Widgets");
    

    3 回复  |  直到 16 年前
        1
  •  0
  •   Community Mohan Dere    9 年前

    您可以将局部视图渲染为字符串,并返回该字符串:

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

    here

        2
  •  0
  •   Darin Dimitrov    16 年前

    alert(ajaxContext.get_response().get_responseData());
    

    get_object() 函数仅适用于JSON内容。

        3
  •  0
  •   Jaco Pretorius    16 年前