Sending data to controller with Ajax

by Sachin Singh


Posted on Monday, 02 March 2020

Tags: How to get Kendo UI components value with jquery How to send ajax in asp.net mvc How to get kendo UI controls values and send it to mvc controller with jquery Ajax

Sending data to Asp.Net Controller from view with Ajax is simple. The Jquery Ajax() method allows us to send asynchronous request to the server.We just need to do some settings that is we need to set the appropriate parameter value ,which the Ajax methods asks.

Some of the useful parameter of Ajax() are as below:-

1.Type:- Here we need to specify the appropriate http verb that is the action we want from Ajax to perform. The common Http verbs are get,post,put and delete.

2.Url:-Here we need to specify the url (path) of the server from where we want to fetch the data or to where we want to send the data. In our scenario the url will be our Action name /controller Name.

3.dataType:-Here we need to specify the data type of the data we are sending to or retrieving from the server. It may be Json,Html or anything like that.

4.data:-Here we need to specify the data we want to send to the server .If we are doing a get request then we don't need to specify it.

5.Cache:-Here we need to specify true/false meaning whether we want our browser to cache it or not.

6.Success:-Here we need to specify a function ,the function which will handle any further stuffs after the success of Ajax request. So here we can manipulate DOM element values with the value we are getting in success function. In short it is a callback function.

We write the Ajax method like below:-


  $.ajax({
            type: "post",
            url:"/home/Save",
            dataType: "json",
            contentType: "application/json;charset=utf-8",
            data: JSON.stringify(model),
            traditional: true,
            cache: false,
            success:function(){}
        })

As you can notice, performing an Ajax request is very simple.

Our challenge is to get or collect data from Kendo UI controls or components ,so that we can send it to Asp.Net MVC controller with Ajax().

Let us understand how can we collect data from Kendo UI helpers with jquery.

@(Html.Kendo().TextBox().Name("txtName")) we get the Textbox value like -> $("#txtName").val()
@(Html.Kendo().CheckBox().Name("chkmale").Label("Male").HtmlAttributes(new { @value = "Male" }))

Intensionally set the value with htmlAttributes

and easily get it like -->

$("#chkmale").val()
@(Html.Kendo().DropDownList().Name("ddl") .DataTextField("textvalue") .DataValueField("NumericValue") )

Generally we set Textfield to string and value field to numeric

and get it like -->

$("#ddl").data("kendoDropDownList").text();for text field $("#ddl").data("kendoDropDownList").val();for value field
@(Html.Kendo().DatePicker().Name("date"))

date picker gives the datetime

which we get like -->

$("#date").data("kendoDatePicker").value();
@(Html.Kendo().Editor().Name("editor"))

Editor is like rich textArea

the value we get like -->

$("#editor").data("kendoEditor").value();

Now when we know how to get value from kendo controls and how to use ajax.Lets create Two methods in controller one to return view and other to save data like below.


  public ActionResult Test()
        {
           
            return View();
        }
 public void Save(User model)
        {
        }

Also create one model class that that has been used in the controller Save method that will catch data send by ajax method from view like below.


    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public string Password { get; set; }
        public DateTime DOB { get; set; }
        public List<socialsites> Socials { get; set; }
        public string Sport { get; set; }
    }
    public class SocialSites
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Now Create the form in the view like below.


    <h2>Test</h2>
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />


    <table style="width:100%;" class="table table-bordered table-responsive-md">
    <thead class="bg-dark text-center text-white">
    <tr>
    <th colspan="2">Registration Form</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>User Name</td>

    <td>@(Html.Kendo().TextBox().Name("txtName"))</td>
    </tr>
    <tr>
    <td>Gender</td>

    <td>
    @(Html.Kendo().RadioButton().Name("Male").Label("Male").HtmlAttributes(new { Name = "rdoGender",value="Male" }))
    @(Html.Kendo().RadioButton().Name("Female").Label("Female").HtmlAttributes(new { Name = "rdoGender",value="Female" }))
    </td>
    </tr>
    <tr>
    <td>DOB</td>

    <td>@(Html.Kendo().DatePicker().Name("dateDOB"))</td>
    </tr>
    <tr>
    <td>Password</td>

    <td>@(Html.Kendo().TextBox().Name("txtPassword").HtmlAttributes(new { type = "password" }))</td>
    </tr>
    <tr>
    <td>Introduce Yourself</td>

    <td>
    @(Html.Kendo().Editor().Name("txtIndro").HtmlAttributes(new { style = "height:200px", aria_label = "editor" })
      .Resizable(resizable => resizable.Content(true).Toolbar(true)))
    </td>
    </tr>
    <tr>
    <td>Favourite Sport</td>

    <td>
    @(Html.Kendo().DropDownList().Name("ddlSports").BindTo(new List<SelectListItem>() {
   new SelectListItem(){Text="Cricket",Value="0"},
    new SelectListItem(){Text="Football",Value="1"},
      new SelectListItem(){Text="Hockey",Value="2"},
        new SelectListItem(){Text="Basketball",Value="3"},
   }).OptionLabel("select"))
    </td>
    </tr>
    <tr>
    <td>You are at</td>

    <td>
    @(Html.Kendo().CheckBox().Name("Twitter").Label("Twitter").HtmlAttributes(new { @name = "Social", value = "Twitter" }))
    @(Html.Kendo().CheckBox().Name("Facebook").Label("Facebook").HtmlAttributes(new { @name = "Social", value = "Facebook" }))
    @(Html.Kendo().CheckBox().Name("Instagram").Label("Instagram").HtmlAttributes(new { @name = "Social", value = "Instagram" }))
    </td>
    </tr>
    <tr>
    <td colspan="2">
    @(Html.Kendo().Button().Name("btnSubmit").HtmlAttributes(new { type = "button", @class = "ml-auto k-button k-primary", style = "height:35px;width:70px;" }).Content("Save"))
    </td>
    </tr>
    </tbody>
    </table>

Lastly send the data with Ajax like below.




I have used Jquery object to send the values.You should notice that jquery object have all properties defined with same name as our User Model Class have.This is because,the MVC model binder tries to bind the model properties values by matching the Name attribute values it receives from the ajax request.

Now run the application you will get the below view rendered in your browser.

View for Ajax Post
View for Ajax Post

Put a debugger in the save method in your controller to check whether you are getting values or not.

Save method in Controller
Getting values in Controller Save method