简体   繁体   中英

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

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.

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