我正在使用timepicki(jquery timepickers之一)将视图中的DateTime值传递给控制器,尤其是ActionResult Create方法。我已经在Sources选项卡下使用F12测试了在视图中用javascript编写的ajax调用,事实上,该值成功存储在函数内部的变量中,但似乎没有将其值传递给控制器。你能帮助我为什么不把它的值传递给控制器吗?任何帮助表示赞赏。
查看:
@model test.Models.Employee
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.MondayId, "Monday: ", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
Start: <input type="text" name="timepicker" class="time_element" id="monStart"/>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" id="submit" onclick=""/>
</div>
</div>
</div>
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script src="@Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/timepicki.js")" type="text/javascript"></script>
<link href="@Url.Content("~/Content/timepicki.css")" rel="stylesheet" type="text/css" />
<script>
$(document).ready(function(){
$(".time_element").timepicki();
});
</script>
<script type="text/javascript">
$("#submit").click(function () {
var monStart = $('#monStart').val();
$.ajax({
url: '@Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart },
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
})
});
</script>
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Employee employee, DateTime? monStart)
{
//codes
}
答案 0 :(得分:1)
您在AntiForgeryToken
来电时错过了ajax
。所以你的电话:
$.ajax({
url: '@Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart},
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
应该是:
var myToken = $('[name=__RequestVerificationToken]').val();
$.ajax({
url: '@Url.Action("Create", "Employees")',
data: { employee: null, monStart: monStart, __RequestVerificationToken : myToken },
type: 'POST',
success: function (data) {
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});