Tk Breen
Tk Breen

Reputation: 157

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>

Upvotes: 12

Views: 57418

Answers (5)

sapana
sapana

Reputation: 156

This is the Razor View

    <div class="editor-field col-md-3">          
        @Html.DropDownListFor(model => model.Servers, 
          Model.AvailableServers,new { @class = "form-control" })  
         @Html.ValidationMessageFor(model => model.SqlServerName)
    </div>

Dynamic DropDown from controller

        List<SelectListItem> ServersAvailable = new List<SelectListItem>();
            bool IdSelected = false;
            ServersAvailable.Add(new SelectListItem { Text = "......Select your server name......", Value = "" });
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                ServersAvailable.Add(new SelectListItem
                {

                    Text = dt.Rows[i].ItemArray[0].ToString(),
                    Value = dt.Rows[i].ItemArray[0].ToString(),
                    Selected = IdSelected
                });
            }

Upvotes: 0

Mehdi Rahimi
Mehdi Rahimi

Reputation: 2546

@andresdescalzo's solution (last one) works with a minor change:

@Html.DropDownListFor(model => model.Type, new SelectList(new string[] {"Football", "Rugby", "Horse Racing"}, "Rugby"), htmlAttributes: new { @class = "form-control" })


First: Add a selected item for dropdown list (e.g. "Rugby")
Second: remove last Model.Type and add htmlAttributes

PS: SelectedList open parentheses closed after selected item of list (here is "Rugby")

Upvotes: 5

Chihuahua Enthusiast
Chihuahua Enthusiast

Reputation: 1580

An addition to the existing answers: If you get the exception "object reference not set to an instance of an object" when implementing @andresdescalzo's solution, you either need to:

  1. Return the model that you are working with as @diwas mentioned
  2. Instantiate a model on the razor page so you can call the method. This is helpful if you are using a ViewModel instead of a simple EF model.

The second can be done like this:

@{ var tempModel = new YourNameSpace.Models.YourModel(); }
@Html.DropDownListFor(model => model.Type, tempModel.TypeList, Model.Type))

Upvotes: 0

Diwas
Diwas

Reputation: 763

The solution provided by @andresdescalzo works only when we pass the model from Controller to the view.

public class SomeController : Controller
{
  public ActionResult SomeAction()
  {
    return View(new SomeModelWithIEnumerationsSelectListItem())
  }
}

Upvotes: 1

andres descalzo
andres descalzo

Reputation: 14967

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))

Upvotes: 24

Related Questions