JQuery AJAX Post In ASP.NET MVC

This article will demonstrate, how to post the data to ASP.NET MVC controller using JQuery AJAX.


In some cases, you may need to apply some actions instantly and reflect on the screen without refreshing your page.
In such cases, we can use the JQuery Ajax Post.


How can we perform JQuery Ajax Post operation in ASP.NET MVC


First of all, what is JsonResult ? Let's answer the question. JsonResult is a type that allows us to return the model we have in the JSON (JavaScript Object Notation) data structure.


Now we will go through the sample scenario in our article. We will have a model named "Student". Then we will examine calling a student with an ID value and calling the whole student using JQuery Ajax.


- Create ASP.NET Web Application


- Create a model class named Student as follows


public class Student
{
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string ClassRoom { get; set; }
}

Create a Controller named StudentController in the Controllers folder. Next step is to add a View for the Controller.


Since we will bring a student with an ID value using Ajax, our View file named "Index.cshtml" will be as follows.


<div class="card">
    <div class="card-body">
        <div class="row form-row">
            <div class="col-12 col-md-6">
                <div class="form-group">
                    <label>Student ID</label>
                    <input type="text" class="form-control" placeholder="Enter Student ID" id="StudentID" name="StudentID">
                </div>
            </div>
            <div class="col-12 col-md-6">
                <div class="form-group">
                    <label>Student Information</label>
                    <p>First Name : <span id="FirstName"></span></p>
                    <p>Last Name : <span id="LastName"></span></p>
                    <p>Class Room : <span id="ClassRoom"></span></p>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="submit-section submit-btn-bottom">
    <button id="BringStudent" type="submit" class="btn btn-primary submit-btn">Send</button>
</div>

We will send the ID value entered from the input with the "StudentID" value to the Action method named "BringStudent" in our Controller class named "StudentController" with JQuery Ajax.


We will get the student with the corresponding ID value as JSON.


[HttpPost]
public JsonResult BringStudent(int studentID)
{
    List students = new List
    {
        new Student { ID = 1, FirstName = "Mike", LastName = "Anderson", ClassRoom = "F-5" },
        new Student { ID = 2, FirstName = "Tom", LastName = "Donald", ClassRoom = "A-1" },
        new Student { ID = 3, FirstName = "Ricky", LastName = "Wasson", ClassRoom = "B-6" },
        new Student { ID = 4, FirstName = "Andy", LastName = "Anderson", ClassRoom = "G-5" },
    };

    Student student = students.FirstOrDefault(o => o.ID == studentID);
    return Json(student, JsonRequestBehavior.AllowGet);
}

As you can see above, we simply create the students and then we select the student with the relevant ID value and send it back with the Json() method.


While passing the student object in the first parameter in the Json() method, we allow this operation by giving the JsonRequestBehavior.AllowGet command in the second parameter.


If we do not use the JsonRequestBehavior.AllowGet command, our object will not be converted to Json data format and we will encounter an error.


Now, let's perform the Post operation to this method with Ajax.


<script type="text/javascript">
    $(document).ready(function () {
        $("#BringStudent").click(function () {
            var val1 = $("#StudentID").val();
            $.ajax({
                type: "POST",
                url: "/Student/BringStudent/",
                data: { studentID: val1 },
                dataType: "json",
                success:function(data){
                    $("#FirstName").html(data.FirstName);
                    $("#LastName").html(data.LastName);
                    $("#ClassRoom").html(data.ClassRoom);
                }
            });
        });
    });
</script>

If we examine the AJAX code block above, with url, we specify that;
- the address to be run as a result of post
- the Post operation will be done with type.
- we will work with dataType in Json data format


If a value is returned as a result of the Post operation with success, the parameter named data in the function defined represents this value.


The point you need to pay attention here is that the data parameter is exactly the same as the Student model's properties.p>
aspnet-mvc-jquery-ajax-1.PNG

tag : View and Controller AJAX in ASP.NET MVC

Note : If you get an error like this "Uncaught ReferenceError: $ is not defined", you are calling your script before the JQuery.
you should put your script after the JQuery. Reference jQuery first.