A191919
A191919

Reputation: 3462

Post datetime to controller

I am trying to send date to controller using ajax but get's null. why?

enter image description here

@{
ViewBag.Title = "Index";
}

<h2>Index</h2>

<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>

<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />

<div class="container">
<div class="row">
    <div class='col-sm-6'>
        <div class="form-group">
            <div class='input-group date' id='datetimepicker1'>
                <input type='text' class="form-control" />
                <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                </span>
            </div>
        </div>
    </div>
    <script type="text/javascript">
        $('#datetimepicker1').datetimepicker({ useCurrent: false });
        $('#datetimepicker1').on("dp.hide", function (e) {
            $.ajax({
                url: "/Home/GetData",
                type: "POST",
                data: JSON.stringify($('#datetimepicker1').data('DateTimePicker').date()),
                contentType: "application/json",
                success: function (result) { alert('Done') },
                error: function (r, e, s) { alert(e) }
            });
        });
    </script>
</div>
</div>

Controller:

public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult GetData(string test)
    {
        return View();
    }
}

Upvotes: 0

Views: 5246

Answers (1)

user3559349
user3559349

Reputation:

You not passing a name/value pair back to the controller method that matches the parameter name (test) and the is no need to stringify the data. Change the ajax script to

$.ajax({
    url: '@Url.Action("GetData", "Home")', // don't hard code your url's 
    type: "POST",
    data: { test: $('#datetimepicker1').data('DateTimePicker').date() },
    // contentType: "application/json", delete this
    success: function (result) { alert('Done') },
    error: function (r, e, s) { alert(e) }
});

And since you posting a DateTime value the controller method should be

[HttpPost]
public ActionResult GetData(DateTime test)
{
    return View();
}

This assumes the the date value is in a format that matches the server culture, or in ISO format ('yyyy-MM-dd HH:mm'), for example by using

data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },

Note that your method is returning a view, but you not doing anything with the html you return (just displaying an alert)

Upvotes: 1

Related Questions