0

Please see the View code below:

<div class="row">
    <div class="col-md-4">
        <form asp-action="MemberView">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Name" class="control-label"></label>
                <input asp-for="Name" class="form-control" />
                <span asp-validation-for="Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="DOB" class="control-label"></label>
                @Html.TextBox("datepicker")                   
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

How do I make @Html.TextBox("datepicker") readonly (so only the datepicker can populate it) i.e. a user cannot type in it. I have spent one hour Googling this and have already looked here: Using DatePicker with .NET

Matthijs
  • 2,483
  • 5
  • 22
  • 33
w0051977
  • 15,099
  • 32
  • 152
  • 329

1 Answers1

1

Add a readonly property by passing an anonymous object as the third argument.

The null (second argument) is there to keep the input value empty. Of course you could fill it if necessary.

@Html.TextBox("datepicker", null, new { @readonly = "readonly" }) 

Note: The @ symbol is required, because 'readonly' is a reserved keyword.

Please keep in mind that the user is able to manipulate the HTML by removing the readonly attribute. Proper value checking in the back-end is required to handle the value safely.

Matthijs
  • 2,483
  • 5
  • 22
  • 33
  • Thanks. However, this just does not work. It simply writes new { @readonly = "readonly" } in the textbox (and the textbox is still editable). Do you have any other ideas? – w0051977 Oct 21 '18 at 17:38
  • You could try the `disabled` property. – Matthijs Oct 21 '18 at 17:39
  • @Html.TextBox("datepicker", "",new { @readonly = "readonly" }) does seem to work (note there are three arguments). However, I do not know why. – w0051977 Oct 21 '18 at 17:39
  • Well, that was my bad. Sorry about that. The *second* argument is the current value for the input. The **third** parameter is for attributes. I've updated my answer. – Matthijs Oct 21 '18 at 17:41
  • Thanks. What is the second parameter for (the default value I guess)? +1. – w0051977 Oct 21 '18 at 17:45
  • The value for the input. Mostly used for edit pages. – Matthijs Oct 21 '18 at 17:45
  • I have asked a follow on question here if you are interested: https://stackoverflow.com/questions/52949847/using-the-html-5-datepicker-with-the-date-input-field – w0051977 Oct 23 '18 at 15:42