开发者

JSON returned using Json() by jquery $.post()

开发者 https://www.devze.com 2023-04-12 21:12 出处:网络
I can\'t work out what I\'m doing wrong - I\'m sure this used to work...: <s开发者_开发百科cript type=\"text/javascript\">

I can't work out what I'm doing wrong - I'm sure this used to work...:

<s开发者_开发百科cript type="text/javascript">
  $("#@containerId form").submit(function (event) {
    event.preventDefault();
    var form = $(this);
    if (form.valid()) {
      $.post(form.attr('action'), form.serialize(), function(data) {
        $("#@containerId").replaceWith(data.result);
      }, "json");
    }
  });      
</script>

I have a function that returns a view result as a string so I can return it as an object within the JSON response:

protected string RenderViewResultToString(ViewResultBase viewResult) {
  using (var sw = new StringWriter()) {
    if (string.IsNullOrEmpty(viewResult.ViewName))
      viewResult.ViewName = ControllerContext.RouteData.GetRequiredString("action");
    ViewEngineResult result = null;
    if (viewResult.View == null) {
      result = viewResult.ViewEngineCollection.FindPartialView(ControllerContext, viewResult.ViewName);
      if (result.View == null)
        throw new InvalidOperationException("Unable to find view. Searched in: " + string.Join(",", result.SearchedLocations));
      viewResult.View = result.View;
    }
    var view = viewResult.View;
    var viewContext = new ViewContext(ControllerContext, view, viewResult.ViewData, viewResult.TempData, sw);
    view.Render(viewContext, sw);
    if (result != null)
      result.ViewEngine.ReleaseView(ControllerContext, view);
    return sw.ToString();
  }
}

So, in my controller I have:

    [HttpPost, ValidateInput(false)]
    public JsonResult Edit(/* stuff */) {
        bool success = true;
        try {
            /* stuff */         
        } catch {
            /* stuff */
            success = false;
        }
        return Json(new { success, result = RenderViewResultToString(/* stuff - call to something that gives a ViewResult */) });
    }

In Chrome, I get: "Resource interpreted as Document but transferred with MIME type application/json." and it renders the JSON in the browser as text. In Firefox/IE, it prompts me to download a file.

What gives?


The form submission isn't getting suppressed. The messages you are getting are from an actual form submission to a page that returns JSON. If you check the browser address bar, you should see the URL is different.

If you run $("#@containerId form") in the console, you should see that you're getting no results. "@" is an invalid character in a selector and needs to be escaped. $("#\\@containerId form") should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号