Search results

Posting the selected dates to the controller

15 Oct 2021 / 1 minute to read

Post back is the action of posting the data back to the submitting page. In the following example, value for the DatePicker from the change event is sent through Ajax post to the controller.

In this example, the content type is “application/json” and the request body is a JSON object. In the action method, you can pass a model as the parameter. The POST method determines how data is sent from the client via the form, to the server.

razor
postback-selected-dates-mvc.cs
Copied to clipboard
@model EJ2_MVC.Controllers.FormData

@Html.EJS().DatePickerFor(model => model.date).Change("submit").Width("200px").Render()

<script>
    function submit(args) {
        var dateStr = args.value.toUTCString(); // Convert to UTC string
        $.ajax({
            type: "POST",
            url: '@Url.Action("ChangeData")',
            contentType: "application/json", // define content type
            dataType: "json",
            data: JSON.stringify({ 'date': dateStr}),   // pass data to controller
        })
    }
</script>
Copied to clipboard
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;

namespace EJ2Sample.Controllers
{
    public class FormData
    {
        public String date { get; set; }
        public DateTime recievedDate { get; set; }
    }
    public class HomeController : Controller
    {
        // GET: /<controller>/
        public ActionResult Index()
        {            
            return View();
        }

        [HttpPost]
        public ActionResult ChangeData(FormData formData)
        {
            //Process using recieved date 
            formData.recievedDate = DateTime.Parse(formData.date);
            return Json(formData);
        }
    }
}