1

On my razor page, I have a simple date picker that looks like this:

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

How would I go about getting the value of that and sending it to my controller?

Whenever I send data to my controller from a razor page, the format always looks something like this:

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

which sends an "item.Id" to my controller called LessonIndex().

So I'm not sure how I'd get the date value and send it.

The controller looks like this:

public IActionResult LessonIndex(datetime startDate) {

    var response = getLessons(startDate);

      return response.Results;
   } 

Is there a specific format I need to use?

Note that the date is not used in a model, it just needs to be sent to a controller.

Thanks!

7
  • does 'lessonStart' correspond to a valid name in your razorpage or controller? Since you listed mvc as one of your targeted tags. Commented Jan 23, 2019 at 1:04
  • I have an idea of what you are trying to do but I need some clarification and some more source if you can provide what your controller looks like. Also do you have a model associated with the page in question? Commented Jan 23, 2019 at 1:14
  • @mvermef lessonStart was just the name I gave the html element. It doesn’t mean anything beyond that. Commented Jan 23, 2019 at 1:39
  • this is a RazorPage or Mvc Controller that you want this to get back to? 2 ways to acheive 1) javascript or 2) post a form. Commented Jan 23, 2019 at 1:41
  • @mvermef I also added the method in the controller that needs the date from the date picker. Please note there is no model associated with this view. Commented Jan 23, 2019 at 1:45

3 Answers 3

1

Assuming this is related to mvc the controller would have a method associated with the post that you would perform to get the data from the form back to the controller. This uses javascript to post data to your LessonIndex() method.

<!--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>
}

this also assumes that the method looks like this


public class LessonController : Controller{

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

}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, what does @inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf do? I've never seen that used before. Is it needed? Thank you
I tried out the code, and after I hit the "Go" button, I get this error: localhost:44304/LessonController/LessonIndex?lessonStart=Invalid%20Date
Right cause the route should be Lesson/LessonIndex?lessonStart="theDateSent" . As for XSRF its cross site request forgery preventative measures, not really required but a good idea all things posted via javascript. This is taken into account automatically if you where using <form asp-antiforgery="true" /> but since the way you are doing this without a form which is fine, javascript has to be used. If LessonController is actually showing up in the url, that route is designed wrong or is malformed.
Oh thank you, I didn't know you had to remove the 'controller' word. thanks! It works now!
1

" Note that the date is not used in a model, it just needs to be sent to a controller. "

You could use the ajax to pass the date as QueryString to the method in the controller.

Here is the test example

<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>
} 

The method in controller

 [HttpPost]
    public IActionResult LessonIndex(DateTime startDate)
    {

        return Json(startDate);
    }

Comments

-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>

1 Comment

Im sorry, but what is .Kendo() ? Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.