Ajax.BeginForm does not call onSuccess

In an ASP.NET MVC 3 application, I use Ajax.BeginForm to send a text message to the 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 the 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 the Javascript function does not work and does not cause a warning, my browser (Firefox) returns me a pop-up window for downloading the application / json file. What is wrong here?

+5
source share
4 answers

Make sure you include the following script page in the page:

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

and that you included unobtrusive javascript in your web.config:

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

This is what helps Ajax.* Helpers such as Ajax.BeginForm .

+19
source

Thanks to "Darin Dimitrov" and his answer for saying a lot about this. But just adding to it, I know that it can be simple, but it bothered me,

My mistake was that I thought that

 jquery.validate.unobtrusive.js 

and

  jquery.unobtrusive-ajax.js 

where they are the same when they are not. Make sure you use "jquery.unobtrusive-ajax.js" found in Nuget.

Microsoft.jQuery.Unobtrusive.Ajax

+3
source

This is a much nicer solution when you give your Id form and then attach the submit event to a separate javascript file (using jQuery) and process the message 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 } }); } }); 
0
source

Source: https://habr.com/ru/post/918790/


All Articles