Reputation: 3515
I have implemented jquery date picker, but I'm struggling with parsing datetime value. Scenario is following, user should select date using jquery datepicker, date should be on following format (dd.MM.yy
), datetime value should be sent to the controller using ajax, and receive (for simplicity of these example) some dummy data over json.
I have following
Views/Shared/EditorTemplates/DateTime.cshtml
@model DateTime
@Html.TextBox("", Model.ToString("dd.MM.yy"), new { @class = "date" })
Views/Home/ @Html.EditorFor(m => m.MyDate)
<script type="text/javascript">
$('#pickDate').click(function () {
var date = $('input[name="MyDate"]').val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { MyDate: date },
url: '/Home/DateManipulation',
success: function (result) { alert('Success'); },
error: function () { alert("error"); }
});
});
</script>
HomeController.cs
[HttpPost]
public JsonResult DateManipulation(string MyDate)
{
DateTime date = DateTime.ParseExact(MyDate, "dd.MM.yy", CultureInfo.InvariantCulture);
var process = //omitting
return Json(process);
}
And on the _Layout.cshtml I have on dom ready
$('.date').datepicker({ dateFormat: "dd.MM.yy" });
I'm not getting date on the controller, error is Invalid JSON primitive: MyDate.
Upvotes: 0
Views: 970
Reputation: 17992
In your call to /Home/DataManipulation/
<script type="text/javascript">
$('#pickDate').click(function () {
var date = $('input[name="MyDate"]').val();
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: { MyDate: date },
url: '/Home/DateManipulation',
success: function (result) { alert('Success'); },
error: function () { alert("error"); }
});
});
</script>
Try replacing data: { MyDate: date }
with data: JSON.stringify({ MyDate: date })
Upvotes: 1