简体   繁体   中英

ASP.Net Core 3: How do I make an @Html.DropDownListFor “read-only” with a default value?

I'm using ASP.Net Core 3.1.

I inherited some "select/option" lists that look like this:

    <div class="form-group" id="Q5_div">
        <label>@Questions.Q5*</label>
        @Html.DropDownListFor(m => m.Answers.Q5, new SelectList(Enum.GetValues(typeof(YesNo))),
          "Select Yes or No",
           new {@class = "custom-select", @id = "Answers_Q5" })
    </div>

All well and good. The user selects "Yes" or "No" from the dropdown, and the value is written to the database.

GOAL:

I'd like to hard code "No", and make the field read-only. Here's what I tried:

    <div class="form-group" id="Q5_div">
        <label>@Questions.Q5*</label>
        @Html.DropDownListFor(m => m.Answers.Q5, new SelectList(Enum.GetValues(typeof(YesNo))),
          "No",
           new { @disabled = "disabled", @class = "custom-select", @id = "Answers_Q5" })
    </div>

Problem

"Answers.Q5" is always null . The DropDownList never gets bound to "Answers_Q5"; the model never gets the value "No".

Q: How can I make an ASP.Net Core @Html.DropDownList "read-only" with a default value?

At Sh.Imran's request, I posted my workarounds:

Goal: Make an ASP.Net Core @Html.DropDownList "read-only" with a default value.

Challenge: Many elements allow the "readonly" attribute; apparently DropDownList doesn't.

The scenario is described here: how to give #readonly in DropdownListfor in asp.net MVC 4?

Option 1:

Make DropDownList @Disabled, add a parallel "input type=hidden" element for the binding:

<div class="form-group" id="Q5_div">
    <label>@Questions.Q5*</label>
    @Html.DropDownListFor(m => m.Answers.Q5, new SelectList(Enum.GetValues(typeof(YesNo))),
      "No",
       new { @disabled = "disabled", @class = "custom-select", @id = "Answers_Q5" })
    <input type="hidden" name="Answers.Q5" value="No"/>
</div>

Option 2:

Substitute @Html.TextBox (which supports "readonly") for DropDownList:

<div class="form-group" id="Q5_div">
    <label>@Questions.Q5*</label>"

I verified both, and chose Option 2. It's less verbose, and easier to maintain.


Addendum:

One other alternative for "Option 1" (use "@Html.DropDownListFor()", mark "disabled"... but still write the default value) is to put all the <input type="hidden"> tags together, at the top of the file.

EXAMPLE:

<input type="hidden" asp-for="Answers.Q5" value="No" /> 
<input type="hidden" asp-for="Answers.Q6" value="Yes" /> 
<input type="hidden" asp-for="Answers.Q7" value="Maybe" />

This can simplify code maintenance, but it still ensures all the default values are written to the database.

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