Posted on 3/2/2020 12:13:46 AM by Admin

Sending data to controller with Ajax

Sending data to an ASP.NET controller from a view with Ajax is simple. The jQuery Ajax() method allows us to send asynchronous requests to the server. We just need to do some settings that is we need to set the appropriate parameter value, which the Ajax methods ask

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

1.Type:- Here we need to specify the appropriate HTTP verb, which is the action we want 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 that will handle any further stuff after the success of the Ajax request. So here we can manipulate DOM element values with the value we are getting in the 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/p>

@(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 we know how to get value from Kendo controls and how to use Ajax. Lets create Two methods in controller, one to return the 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 a jQuery object to send the values. You should notice that the jQuery object has all the properties defined with the same name as our user model class.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/p>

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/figcaption>

Sharpen Your Skills with These Next Guides