Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a html select box with razor

I have a html selector, and I want to use the selected value for my "model => model.type" in my form. Is there a way to set the value in my @Html.EditorFor(model => model.type) to the value of the selector?

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>Bet</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.type)
    </div>
    <div class="editor-field">

        <select id ="type">
  <option value="Football">Football</option>
  <option value="Rugby">Rugby</option>
  <option value="Horse Racing">Horse Racing</option>
</select>

        @Html.EditorFor(model => model.type)
        @Html.ValidationMessageFor(model => model.type)

    </div>



    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
like image 651
Tk Breen Avatar asked Dec 14 '12 18:12

Tk Breen


1 Answers

You can try with this options:

Model:

public string Type { get; set; }

public IEnumerable<SelectListItem> TypeList
{
    get
    {
        return new List<SelectListItem>
        {
            new SelectListItem { Text = "Football", Value = "Football"},
            new SelectListItem { Text = "Rugby", Value = "Rugby"},
            new SelectListItem { Text = "Horse Racing", Value = "Horse Racing"}
        };
    }
}

HTML (Razor):

@Html.DropDownListFor(model => model.Type, Model.TypeList)

OR

HTML (Razor):

@Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, Model.Type))
like image 168
andres descalzo Avatar answered Sep 23 '22 10:09

andres descalzo