Ajax form submit in asp.net MVC

Here we learn how to submit Ajax Form using Jquery in Asp.net MVC, to keep the content more focused on Ajax Form, I have removed the validation details, so that the content does not looks long and remain focused on Ajax

Step 1: Let’s design a simple Ajax form with just one textbox and AjaxOptions, we will see how to submit form using ajax jquery!

Ajax.BeginForm is built-in method which takes many parameters, one important parameter AjaxOptions class, which has multiple parameters option while creating a new instance of that class.

Ajax form submit example

This is how you can create form in razor view.

@using (Ajax.BeginForm("ajaxPostActionName", "controllerName", FormMethod.Post,
    new AjaxOptions
    {
        OnSuccess = "OnCommentpostSuccess",
        OnFailure = "OnCommentpostFailure",
        OnComplete = "OnCommentpostComplete",
        UpdateTargetId = "commentFormContainer"
    }))
{
@Html.AntiForgeryToken()
Name :  @Html.TextBox("txtCName")
<input type="submit" value="Post Ajax" />
}
 
JavaScript to handle Ajax call

Step 2: Add reference of required Jquery files and write Javascript function

<script src="~/scripts/jquery-1.7.1.js"></script>
<script src="~/scripts/jquery.unobtrusive-ajax.min.js"></script>
                
<script>
    function OnCommentpostSuccess() {
        $("#commentFormContainer").innerHTML = "Posted successfullly";
    }
    function OnCommentpostFailure() {
        alert("Posting error occured");
        $get("#commentFormContainer").innerHTML = "Posting Fail";
    }
    function OnCommentpostComplete() {
        $("#commentFormContainer").innerHTML = "Done! Thankyou!";
    }
</script>
ActionResult to handle Ajax Post

Now we need to write code in controller to capture ajax post form data, this can be done either in ActionResult or JsonResult. In first example we write an ActionResult to capture form data. parameter FormCollection contain form data.

Step 3: Let's look at the code of ActionResult and see how to return Content(_message)

[HttpPost]
[ValidateAjaxAntiForgeryToken]
public ActionResult ajaxPostActionName(FormCollection model)
{
    string _message = null;
    StringBuilder _str = new StringBuilder();
    _str.Append("<div style='padding:10px;font-size:15px;'>");
    _str.Append(string.Format("Name: {0}", model["txtCName"]));
    _str.Append(string.Format("Date Time: {0}", DateTime.Now));
    _str.Append("</div>");
                
    _message = string.Format("Thanks {0}, Comment posted successfully on {1}", model["txtCName"],DateTime.Now);
    return Content(_message);
}
JsonResult to handle Ajax Post

Step 4: Write a JsonResult and return Json(_message)
. When you want to return JSON from your controller you need a JsonResult instead of ActionResult. Take a look at JSON result example from Asp.net mvc ajax form

[HttpPost]
[ValidateAjaxAntiForgeryToken]
public JsonResult ajaxPostActionName(FormCollection model)
{
string _message = null;
StringBuilder _str = new StringBuilder();
_str.Append("<div style='padding:10px;font-size:15px;'>");
_str.Append(string.Format("Name: {0}", model["txtCName"]));
_str.Append("</div>");
                
// Send email
// update /insert database                
_message = string.Format("Thanks {0}, Comment posted successfully on {1}", model["txtCName"],DateTime.Now);                
return Json(_message);
}

The difference between above two method is ActionResult returns plain string, and JsonResult return Json object, so if you have a custom object to return to GUI, JsonResult would be preferable

Remember to use UpdateTargetId property in your Ajax function to update the GUI with message from controller.

Add AntiForgeryToken in Ajax post

So far, we have seen how to submit ajax form, now another important aspect to make sure that the form is safe from CSRF (cross-site request forgery) attacks.

Like in non ajax form we could simply add @Html.AntiForgeryToken(), but for jquery ajax post Anti Forgery Token implementation is done little differently.

We need to write a small function like example below in our razor file, which will return a string value.

@functions{
    public string getAntiForgeryValue()
    {
        string cookieToken, formToken;
        AntiForgery.GetTokens(null, out cookieToken, out formToken);
        return cookieToken + ":" + formToken;
    }
}

Now we need to add the above token value in ajax form header.

$.ajax(
{
    url: "page-or-view-name",
    data: JSON.stringify(model_data),
    type:"post",
    dataType: "json",
    success: function(result){
        $("#div1").html(result);
    },
    headers: {
        'RequestVerificationToken': '@getAntiForgeryValue()'
    }
});

In controller action we can add AjaxAntiForgeryToken as attribute like [ValidateAjaxAntiForgeryToken] we have specified in above code.

You can write a method to validate the token values using AntiForgery.Validate(cookieToken, formToken); method, receive the values from HttpRequestMessage object.

void ValidateRequestHeader(HttpRequestMessage request)
{
    string cookieToken = "";
    string formToken = "";
    IEnumerable>string< tokenHeaders;
    if (request.Headers.TryGetValues("RequestVerificationToken", out tokenHeaders))
    {
        string[] tokens = tokenHeaders.First().Split(':');
        if (tokens.Length == 2)
        {
            cookieToken = tokens[0].Trim();
            formToken = tokens[1].Trim();
        }
    }
    AntiForgery.Validate(cookieToken, formToken);
}

Learn more about AntiForgery and CSRF Attacks.

You also should learn

 
Asp.net MVC Ajaxform Example
Aspnet MVC Training
Asp.net MVC tutorials, learn model view controllers with c#, develop database driven web application using Asp.net MVC framework.
Hire .Net Developer
Free Tutorials
ASP.NET MVC Interview Questions Answers
Asp.Net MVC C# Examples | Join Asp.Net MVC Course | Asp.net Core Tutorial