简体   繁体   中英

Edit and Update in Dropdownlist mvc4

I am trying to implement edit and update in dropdownlist in my application. The list of values for the dropdownlist are displayed from the model. But the selected value is not displayed on dropdownlist. The selected value is also populated as the list of values in dropdownlist.

my model :

public string State
public SelectList RegionList { get; set; }
public class Region
{
 public string ID { get; set; }
 public string Name { get; set; }            
}

View

@foreach (var item in Model.AddressList)
{
    @Html.DropDownListFor(model => item.State, new SelectList(Model.Address.RegionList, "Value", "Text", Model.Address.RegionList.SelectedValue))                                                     
}

Note :
item.State is populated but the value is not displayed
model.address.regionlist is populated and displayed

Controller

public ActionResult EditAddress(AddressTuple tmodel,int AddressID)
{
    int country;
    string customerID = 1;
    List<AddressModel> amodel = new List<AddressModel>();
    amodel = GetAddressInfo(customerID, AddressID); // returns the selected value for dropdown
    foreach (var item in amodel)
    {
        country = item.CountryId;
    }            
    List<Region> objRegion = new List<Region>();
    objRegion = GetRegionList(id); // returns the list of values for dropdown
    SelectList objlistofregiontobind = new SelectList(objRegion, "ID", "Name", 0);
    atmodel.RegionList = objlistofregiontobind;

    tmodel.Address      = atmodel;
    tmodel.AddressList  = amodel;
    return View(tmodel);
}

For edit in dropdownlist, the list of values are displayed. but the selected value is not displayed. What is the mistake in my code .Any suggestions.

EDIT :

@Html.DropDownListFor(model => model.State, new SelectList(Model.RegionList, "ID", "Name",Model.State))

This

model => item.State

is not going to work, because it hides from the html helper the fact that value for the drop down is taken from the model. Correct way to implement this is with replacing foreach with for :

@for (int i=0; i<Model.AddressList.Count; i++)
{
    @Html.DropDownListFor(model => model.AddressList[i].State, new SelectList(Model.Address.RegionList, "Value", "Text", Model.Address.RegionList.SelectedValue))                                     
}

Assuming that the AddressList property is an IList<Something> try like this:

@for (var i = 0; i < Model.AddressList.Count; i++)
{
    @Html.DropDownListFor(
        model => model.AddressList[i].State, 
        new SelectList(Model.Address.RegionList, "Value", "Text")
    )
}

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