Ajax.BeginForm return Json for message

1.4k Views Asked by At

I am using jquery unobtrusive ajax and MVC Ajax.Beginform() to validate a form via C# server side. I'm always replacing the form with itself.

It's all working fine, but I am wondering:

Let's say my form is triggering a "save to database" action and this action succeeded. There are no errors in the form so I don't want to post back the form to the client, but rather a JSON message that triggers a success dialog on the front end. The problem is that the form replace is always happening. How can I force it not to replace my form when I get json back from the server?

I guess what I'm asking is: how can I NOT have the div updated but just do some other code instead?

I know about onSuccess, but it is fired after the DIV replace, I want to skip the replace.

2

There are 2 best solutions below

0
On

You should jQuery ajax to post the form instead of Ajax.Beginform for this kind of functionality. The point of Ajax.BeginForm is to post the form and update a given target. If you want to return either a partial view or a JSON object, you should do the page replacing and success dialog triggering with jQuery.

0
On

You may have to implement custom replace functionality

  • Server side:

1) Create a response model that will contain the status of your response with corresponding message

public class ReposnseModel
{
    public bool isSuccess {get; set;}
    public string SuccessMessage {get;set;}
    public string ErrorMessage {get;set;}
}

2) Your form have to be rendered through partial view so you could return only it's content

public ActionResult DoWork(Model model)
{

//if success:
...
return Json(new ReposnseModel{isSuccess = true, SuccessMessage = "Success"});

//if lets say model is not valid or some other error:
return PartialView("YourPartialViewForm",model)

}
  • Client side

Register Ajax.BeginForm onSuccess callback with something like this:

  function Callback(data) {
    if (data != null) {
        if (data.isSuccess != undefined) { //means that the data is a serialized ReposnseModel and not a form content
            if (data.isSuccess) {                
                alert(data.SuccessMessage);               
            }else
            {              
                alert(data.ErrorMessage);
            }
        }
        else { //otherwise data is a form content, so it needs to replace the current content  
            $('#formContainer').html(data);
        }
     }
  }