获取html 5 date输入字段并传递给.net控制器

时间:2019-01-22 21:08:20

标签: razor asp.net-core-mvc asp.net-core-2.0

在我的剃须刀页面上,有一个简单的日期选择器,如下所示:

<input type="date" name="lessonsStart">

我将如何获取该值并将其发送给我的控制器?

每当我从剃须刀页面向控制器发送数据时,格式始终如下所示:

<a asp-action="LessonIndex" asp-route-id="@item.Id">@Html.DisplayFor(modelItem => item.Name)</a>

它将“ item.Id”发送到我的名为LessonIndex()的控制器。

所以我不确定如何获取日期值并将其发送。

控制器看起来像这样:

public IActionResult LessonIndex(datetime startDate) {

    var response = getLessons(startDate);

      return response.Results;
   } 

我需要使用一种特定的格式吗?

请注意,模型中没有使用日期,只需将其发送到控制器即可。

谢谢!

3 个答案:

答案 0 :(得分:1)

假设这与mvc相关,则控制器将具有与该帖子相关联的方法,您将执行该方法以将数据从表单返回到控制器。这使用javascript将数据发布到您的LessonIndex()方法中。

<!--top of your page.-->
@inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
@functions{
    public string GetAntiXsrfRequestToken()
    {
        return Xsrf.GetAndStoreTokens(Context).RequestToken;
    }
}
<input type="date" id="lessonStart" name="lessonStart" />
<input type="Submit" id="PostButton" name="PostButton" Value="Go" />
@section Scripts{ // razor section at the bottom of mvc page 'cshtml'.
<script type="javascript">
 $(function(){   
   $("#PostButton").click(function(){
      var url = '@Url.Action("LessonIndex", "Lesson")';  //assuming controller is named Lesson
       var date= new Date(this.value).ToDateString();
      $.ajax({
        url: url, 
        type: "POST",
        data: "lessonStart=" + date,
        headers:{
        "RequestVerificationToken": '@GetAntiXsrfRequestToken()'
        },
        success: function(response){
           console.log(response);
        },
        error: function(e){
          console.log(e.error);
        }
      });
   });
 }
</script>
}

这还假定该方法看起来像这样


public class LessonController : Controller{

 [HttpPost]
 [AutoValidateAntiforgeryToken]
 public IActionResult LessonIndex(DateTime lessonStart){
          var response = getLessons(lessonStart);
    return View(response.results);
 }

}

答案 1 :(得分:1)

“请注意,日期未在模型中使用,只需将其发送到控制器即可。”

您可以使用ajax将日期作为QueryString传递给控制器​​中的方法。

这是测试示例

<input type="date" name="lessonsStart" id="lessonsStart">

@section Scripts
{
<script type="text/javascript">
    $("#lessonsStart").change(function () {
        var inputDate = new Date(this.value).toDateString();
        $.ajax({
            type: "post",
            url: "/ControllerName/lessonindex?startdate=" + inputDate,
            success: function () { }
        });
    });

</script>
} 

控制器中的方法

 [HttpPost]
    public IActionResult LessonIndex(DateTime startDate)
    {

        return Json(startDate);
    }

答案 2 :(得分:-1)

    <div class="demo-section k-content">
    <h4>Remind me on</h4>
@(Html.Kendo().DateTimePicker()
        .Name("datetimepicker")
        .Value(DateTime.Now)
        .HtmlAttributes(new { style = "width: 100%", title = "datetimepicker" })
        .DateInput()
)
</div>