我正在尝试使用ajax向控制器发送日期但是得到null。为什么呢?
@{
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();
}
}
答案 0 :(得分:1)
您没有将名称/值对传递回与参数名称(test
)匹配的控制器方法,并且不需要对数据进行字符串化。将ajax脚本更改为
$.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
值,因此控制器方法应为
[HttpPost]
public ActionResult GetData(DateTime test)
{
return View();
}
这假定日期值采用与服务器文化匹配的格式,或采用ISO格式('yyyy-MM-dd HH:mm'
),例如使用
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
请注意,您的方法正在返回一个视图,但您没有对返回的html执行任何操作(仅显示警报)