How to turn a Selectlist into Html.SelectListFor()

2019-07-08 01:41发布

问题:

I need the following to be turned into a @html helper for a drop down list.

<select size="30" class="scrollableinside" id="CustomerSelect">
    @foreach (var customer in Model.Customers)
    { 
        <option  value=@customer.CustomerContacts.First().CustomerContactID>@customer.CustomerName &#09;&emsp;&#09; @customer.CustomerContacts.First().Phone</option>
    }
</select>

Since I'm doing this a little unnorthodox with the .First() and the 2 pieces of data being put into the list I'm not really sure how to make a @Html.SelectListFor for this.

@Html.DropDownListFor(model => model.CustomerID, new SelectList(Model.Customers, "CustomerID", "What do I put here"))

回答1:

you should try this

public class IndexViewModel
{
    // Stores the selected value from the drop down box.
    [Required]
    public int CountryID { get; set; }

    // Contains the list of countries.
    public SelectList Countries { get; set; }
}

public class HomeController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        IndexViewModel viewModel = new IndexViewModel();
        viewModel.Countries = new SelectList(GetCountries(), "ID", "Name");
        return View(viewModel);
    }

    [HttpPost]
    public ActionResult Index(IndexViewModel viewModel)
    {
        viewModel.Countries = new SelectList(GetCountries(), "ID", "Name");
        if (!ModelState.IsValid)
            return View(viewModel);

        //TODO: Do something with the selected country...
        CMSService.UpdateCurrentLocation(viewModel.CountryID);

        return View(viewModel);
    }
}

In View

@Html.DropDownListFor(x => x.CountryID, Model.Countries)

or you can use another

@Html.DropDownListFor(x => x.CountryID, Model.Countries, "- please select -")


回答2:

@Html.DropDownListFor(model => model.CustomerID,new SelectList(Model.Customers, "datavaluefield","datatextfield", Model.CustomerID))