将日期时间发布到控制器 [英] Post datetime to controller
问题描述
我正在尝试使用ajax将日期发送到控制器,但get为空.为什么?
I am trying to send date to controller using ajax but get's null. why?
@{
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>
控制器:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult GetData(string test)
{
return View();
}
}
推荐答案
您无需将名称/值对传递回与参数名称(test
)匹配的控制器方法,并且不需要对数据进行字符串化.将ajax脚本更改为
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) }
});
由于您发布了DateTime
值,因此控制器方法应为
And since you posting a DateTime
value the controller method should be
[HttpPost]
public ActionResult GetData(DateTime test)
{
return View();
}
这假定日期值采用与服务器区域性相匹配的格式,或者采用ISO格式('yyyy-MM-dd HH:mm'
),例如通过使用
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') },
请注意,您的方法正在返回视图,但是您对返回的html不做任何操作(仅显示警报)
Note that your method is returning a view, but you not doing anything with the html you return (just displaying an alert)
这篇关于将日期时间发布到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!