MVC Razor - Default Value as Current date for text

2019-06-15 05:24发布

问题:

I have a Textbox with type as date. I am trying to set default value of the textbox to current date.

@Html.TextBoxFor(x => x.Date, new { @id = "Date", @type = "date", 
                                    @value = DateTime.Now.ToShortDateString() })

The above line doesn't set default value. How to set default value as current date?

回答1:

As Stephen Muecke said, you need to set the property's value on the model.

// in controller method that returns the view.
MyModel model = new MyModel();
model.Date = DateTime.Today;

return View(model);

And your Razor would be:

@Html.TextBoxFor(x => x.Date, "{0:yyyy-MM-dd}", new { @class = "form-control", @type = "date"})

Note that the id and the name properties should be automatically assigned to the property name when using a For method, such as @Html.TextBoxFor(), so you don't need to explicitly set the id attribute.



回答2:

It's better way to manage in view

@Html.TextBoxFor(x=> x.Date, new { @Value = @DateTime.Now.ToShortDateString() })


回答3:

Another Solution:

 @Html.TextBoxFor(model=>model.CreatedOn, new{@value= System.DateTime.Now})

It works on my end, sure it will work on yours.



回答4:

 $(document).ready(function () {
        var dateNewFormat, onlyDate, today = new Date();

        dateNewFormat = today.getFullYear() + '-';
        if (today.getMonth().length == 2) {

            dateNewFormat += (today.getMonth() + 1);
        }
        else {
            dateNewFormat += '0' + (today.getMonth() + 1);
        }

        onlyDate = today.getDate();
        if (onlyDate.toString().length == 2) {

            dateNewFormat += "-" + onlyDate;
        }
        else {
            dateNewFormat += '-0' + onlyDate;
        }

        $('#mydate').val(dateNewFormat);
    });