0

I'm new to MVC and I'm creating a Registration form for my app and I want to add a dropdownlist and I coded ahtml dropdownlist like given below

                <select id="drpType">
                    <option value="0">Single</option>
                    <option value="1">Married</option>
                </select>

And I want to get the selected value how can I achieve that and how to create a default @Html.DropDownList in MVC for the above scenario

  • Worth to read: http://stackoverflow.com/questions/3057873/how-to-write-a-simple-html-dropdownlistfor – Fendy May 08 '13 at 11:08

1 Answers1

4

You should give your dropdown a name (the id is not necessary):

<select id="drpType" name="drpType">
    <option value="0">Single</option>
    <option value="1">Married</option>
</select>

and then in the corresponding controller action to which the form is submitted you could have a parameter with the same name which will contain the selected value:

[HttpPost]
public ActionResult SomeAction(string drpType)
{
    // ... drpType will contain the selected value (0 or 1)
}

But the correct way to achieve this is to use a view model:

public class MyViewModel
{
    [Display(Name = "Marital status")]
    public string SelectedMaritalStatus { get; set; }

    public IEnumerable<SelectListItem> MaritalStatuses
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "0", Text = "Single" },
                new SelectListItem { Value = "1", Text = "Married" },
            };
        }
    }
}

and then you could have a controller with 2 actions (one for rendering the form and one for processing the results):

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel();
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        // ... model.SelectedMaritalStatus will contain the selected value (0 or 1)
    }
}

and now you could have a strongly typed view in which you can use the DropDownListFor helper:

@model MyViewModel
@using (Html.BeginForm())
{
    <div>
        @Html.LabelFor(x => x.SelectedMaritalStatus)
        @Html.DropDownListFor(x => x.SelectedMaritalStatus, Model.MaritalStatuses)
    </div>
    <button type="submit">OK</button>
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928