如何将Selectlist转换为Html.SelectListFor()

时间:2013-04-05 05:11:38

标签: c# asp.net-mvc razor

我需要将以下内容转换为下拉列表的@html帮助器。

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

由于我正在做这个有点非正统的.First()和2个数据被放入列表中我不太确定如何为此创建@ Html.SelectListFor。

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

2 个答案:

答案 0 :(得分:4)

你应该试试这个

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

在视图中

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

或者您可以使用其他

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

答案 1 :(得分:-1)

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