duffyjune February 2016

how do i select value from dropdownlist to mode or to controller mvc

Model

public class Company
{
    public int ID { get; set; }
    ....
    public int WorkZoneID { get; set;  }
    public IEnumerable<SelectListItem> WorkZones { get; set; }

Controller:

ViewBag.Workzones = cmpRep.GetWorkzoneDrop();

Repository:

public List<SelectListItem> GetWorkzoneDrop()
{
    SqlDataReader DR;
    DR = Ado.ExecDataReaderProc("WorkZoneSelectActive");
    List<SelectListItem> selectWorkZoneListItems = new     List<SelectListItem>();
    CompanyVMList C = new CompanyVMList();
    C.Companies = new List<Company>();
    while (DR.Read())
    {
        SelectListItem selectListItem = new SelectListItem
        {
            Text = Convert.ToString(DR["Name"]),
            Value = Convert.ToString(DR["ID"]),
        };
        selectWorkZoneListItems.Add(selectListItem);
    }
    return selectWorkZoneListItems;
}

View

@Html.DropDownList("Workzones")

I want to assign selected dropdownlist value to int work zone int the mode how do i select value from dropdownlist to model or to controller

Answers


Stephen Muecke February 2016

You need to bind your dropdownlist to property WorkZoneID

@Html.DropDownListFor(m => m.WorkZoneID, Model.Workzones)

and if your wanting to preselect an option, you need to set the value in the controller before you pass the model to the view. And since your model contains a property for the SelectList, then use it (don't use ViewBag)

Company model = new Company
{
    WorkZoneID = 1 // set to a value that matches one of your options
    Workzones = cmpRep.GetWorkzoneDrop();
};
return View(model);

and when you submit to

[HttpPost]
public ActionResult Edit(Company model)

the value of model.WorkZoneID will contain the value of the selected option.

Post Status

Asked in February 2016
Viewed 1,627 times
Voted 12
Answered 1 times

Search




Leave an answer