How to pass model's nullable date format data to the view in editable form? problem is when i use input type and use value="" this does not display the datepicker if date is null and if i use this;@Html.TextBoxFor(model => model.ValidFrom, "{0:MM/dd/yyy;

Milan Bishowkarma 0 Reputation points
2023-12-10T12:01:20.94+00:00

problem is when i use <input class="form-control" value="@(Model.ValidFrom)" name="ValidFrom"> this does not display the datepicker if existing value of date is null and if i use this; @Html.TextBoxFor(model => model.ValidFrom, "{0:MM/dd/yyyy}", new { type = "date" }) this does not display the existing value of date only display datepicker; I am doing project on asp.net mvc core.

Developer technologies .NET Entity Framework Core
Developer technologies ASP.NET ASP.NET Core
Developer technologies ASP.NET Other
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 30,126 Reputation points
    2023-12-10T12:40:14.77+00:00

    I assume you are using the browser's date picker not a jQuery date picker. The first thing you should do is read the documentation to learn how the date type works.

    <input type="date">

    Your HTML is invalid it is missing the type="date", it missing the date format, and it not clear what ValidForm is.

    <input class="form-control" value="@(Model?.ValidFrom)" name="ValidFrom">

    The HTML helper is using the wrong date format. The date format should be yyyy-MM-dd as illustrated in the linked documentation.

    Example

    Model

        public class DateModel
        {
            public DateTime? MyDate { get; set; }
        }
        ```
    
    Controller
    
    ```csharp
        public class DateExController : Controller
        {
            // GET: DateEx
            public ActionResult Index()
            {
                DateModel myModel = new DateModel() { MyDate = DateTime.Now };
                return View(myModel);
            }
        }
    

    View

    @model MvcDemo2.Models.DateModel
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    <div>
        <input type="date" value="@Model?.MyDate.ToString("yyyy-MM-dd")" name="MyDate" />
    </div>
    <div>
        @Html.TextBoxFor(t => t.MyDate, "{0:yyyy-MM-dd}", new { type = "date" })
    </div>
    
    
    

    To test null

            public ActionResult Index()
            {
                DateModel myModel = new DateModel(); //{ MyDate = DateTime.Now };
                return View(myModel);
            }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.