How to turn a Selectlist into Html.SelectListFor()

江枫思渺然 提交于 2020-01-15 03:14:07

问题


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))


来源:https://stackoverflow.com/questions/15826371/how-to-turn-a-selectlist-into-html-selectlistfor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!