简体   繁体   中英

ASP.Net Html.TextBox with Dates

I am trying to pass 2 date parameters from the View to the Controller.

View

      <div class="col-md-4">
            <p>Date From:</p>
            @Html.TextBox("ExpDateFrom", ViewBag.ExpDateFrom as DateTime)
        </div>
        <div class="col-md-4">
            <p>Date To:</p>
            @Html.TextBox("ExpDateTo", ViewBag.ExpDateTo as DateTime)
            <input type="submit" value="Find" />
        </div>

Controller

public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, DateTime dateOfExposureFrom, DateTime dateOfExposureTo)

Obviously right now this isn't going to work. I'm not even sure if you should use Html.TextBox for this, but even if you can there is an issue with using DateTime because it is not nullable.

How do I handle this? If I need to completely rework my approach that is fine. I just need to pass 2 date parameters from a view to a controller.

Use reusable model - this will make things easier during further development.

public class SearchModel 
{
public string SortOrder { get; set; }
public string CurrentFilter { get; set; }
public string SearchString { get; set; }
public int? Page { get; set; }
public DateTime DateOfExposureFrom { get; set; }
public DateTime DateOfExposureTo { get; set; }
}

Then controller

public ActionResult Index(SearchModel model)

Then view

@model SearchModel

<div class="col-md-4">
   <p>Date From:</p>
   @Html.TextBoxFor(m => m.DateOfExposureFrom, new { @class = "form-control" })
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM