public void Post([FromBody]DateTime value)
{
// do something
}
值应始终采用yyyy-MM-dd格式
答案 0 :(得分:0)
我相信当你想要验证的不仅仅是类型匹配的事实,而是从请求主体作为基元传入的数据与某些所需的格式匹配时,必须在action方法中进行验证,如果它不是在客户端级别完成的。这是我想出的一个似乎提供了理想行为的尝试。
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/bootstrap.js"></script>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<link href="~/Content/bootstrap-theme.css" rel="stylesheet" />
<script src="~/Scripts/question2ClientController.js"></script>
</head>
<body>
<div>
<button id="submit" class="btn btn-primary">submit</button>
<input id="mydate" type="text" size="10" />
</div>
</body>
</html>
question3bclientcontroller.js文件中的内容
var request = function (event) {
var ajaxOptions = {};
ajaxOptions.url = "/api/question3api";
ajaxOptions.type = "POST";
ajaxOptions.data = {'' : '' + event.data.val()};
ajaxOptions.success = function (result) {
console.log(result);
};
ajaxOptions.error = function (jqXHR) {
console.log("found error");
console.log(jqXHR);
};
$.ajax(ajaxOptions);
}
$(function () {
var date = $("#mydate");
$('#submit').click(date, request);
})
Api控制器操作方法
public IHttpActionResult PostDate([FromBody]string dateString)
{
try
{
DateTime myDate = DateTime.ParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return Ok(HttpStatusCode.NoContent);
}
catch (Exception e)
{
return BadRequest("Unable to parse value in post to DateTimeString");
}
}