开发者

Ajax.BeginForm doesn't call onSuccess

In ASP.NET MVC 3 application I use Ajax.BeginForm to post writed text to controller.

@using (Ajax.BeginForm("Post", "Forum", new {threadId = Model.Thread.Id  }, new AjaxOptions { OnSuccess = "PostReply" }))
{
    <div id="reply-area">
        <h3 style="border-bottom:1px solid black">POST REPLY</h3>

        <span id="post-error" class="error-message"></span>
        <textarea rows="1" cols="1" id="post-textarea" name="Content">    </textarea>

         <input type="submit" class="button" value="Submit"/>

     </div>
}

In controller I have

 [HttpPost]
 public ActionResult Post(int threadId,PostModel model)
 {
     bool Success = false;
     if (ModelState.IsValid)
     {
        Success=Unit.ForumFacade.CreatePost(Unit.ForumFacade.GetThreadByID(threadId), model.Content,  CurrentUserId);
        if (Success == true) return View("PostSuccess");
    }

    return Json("fsdfds");
}

And in javascript I have this

function PostReply(isRequestSuccessed) {
    alert("asdasd");
    if (isRequestSuccessed==false) {
        $("#post-error").html("Please Try Again");
    }
    else
    {
        $("#post-error").html("");
    }
}

The problem is that Javascript's function doesn't firing and isntead the alert, my browse开发者_开发问答r(Firefox) returns me pop-up to download application/json file. What is wrong here?


Make sure you have included the following script to your page:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

and that you have enabled unobtrusive javascript in your web.config:

<add key="UnobtrusiveJavaScriptEnabled" value="true" />

This is what makes Ajax.* helpers such as Ajax.BeginForm to work.


Thanks to "Darin Dimitrov" and his answer for pointing out a lot about this. But just adding to it, I know this might be simple but this got me,

My mistake was that I thought

jquery.validate.unobtrusive.js

and

 jquery.unobtrusive-ajax.js

where the same when they aren't. Make sure you use the "jquery.unobtrusive-ajax.js" found in Nuget.

Microsoft.jQuery.Unobtrusive.Ajax


It is a much nicer solution when you give your form an Id and then attach the submit event in a separate javascript file (using jQuery) and handle the post there

html:

@using (Ajax.BeginForm("Post", "Forum", new {threadId = Model.Thread.Id  }, new {id = "formid" }))
{
 ...

Javascript:

$("#formid").submit(function (e) {
    e.preventDefault();
    if ($(this).valid()) {
        $.ajax({
            type: "POST",
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function (result) {
                //do your success logic
            }
        });
    }
});


here the best solution i have found 100% fix..

http://www.learnsharecorner.com/asp-net/ajax-begin-form-onsuccess-is-not-working-asp-net-mvc/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜