开发者

View, jQuery AJAX, Colorbox, parsingerror

  • let's say I have an actionlink on a page (let's call it MainPage).
  • Actionlink points to an action method that returns View (lets call it PopupView).
  • And script on the MainPage's document.ready() says: "attach colorbox plugin to the actionlink element, so when user clicks on it, PopupView would open".
  • PopupView has a form :

    @using (Html.BeginForm("SavePopupData", "Home", FormMethod.Post))
    
  • Also PopupView overrides default submit behavior:

    $("form[action$='SavePopupData']").submit(function () {  
    
      $.ajax({
        url: $(this).attr("action"),
        contentType: 'application/json; charset=utf-8',
        type: "POST",
        success: function (data, textStatus, jqXHR) { alert('success!'); },
        complete: function (jqXHR, textStatus) { alert('complete!') },
        data: JSON.stringify(someData),
        dataType: "json",
        error: function (jqXHR, textStatus, errorThrown) { alert(textStatus); }
       });
    
      return false;
    }
    
  • Let's see what's in SavePopupData action method:

    [HttpPost]
    public ActionResult SavePopupData(SomeDataType someData)
    {
       bool result = _dal.SavePopupData(someData);
       return new JsonResult { Data = result };
    }
    

Now everything here works as intended. Well, almost everything. on Submit if you put a breakpoint on SavePopupData action method, you can see that data safely gets to the server, gets parsed alright and _开发者_JAVA技巧dal returns result. And everything works fine.

But when it gets back to the client success callback never gets fired, but alert in error callback reports about parsing error.

Strangely if you leave everything as is, and only get rid of the colorbox stuff, it will work. Although it will open the form in the new window (which is not what I want).

What happens with colorobox enabled? Technically it kinda creates a popup as a part of the MainView page. I can't even debug the script of PopupView, because neither Firebug nor Chrome dev tools recognize it, and there is no such script in scripts list. Yet in runtime it still works.

Have you guys any clue what that can be? I think it might be something to do with context in $.ajax. But what should I pass into it, I dunno. Help me please


You should be returning a Json result and not a JsonResult from you controller action.

[HttpPost]
public ActionResult SavePopupData(SomeDataType someData)
{
   bool result = _dal.SavePopupData(someData);
   return Json(new { Data = result });
} 

I stand corrected but, with your current approach, this will fail client side, since the Data property of the JsonResultis not a key/value pair whereas in the above code it is. The difference is very subtle causes many headaches. You could change your current method to

return new JsonResult { Data = new {Data = result} }; 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜