SelectList not从模型中选择保存的值

时间:2015-12-04 19:14:20

标签: c# asp.net-mvc razor selectlist

我有一个选择List,它应该默认从模型中保存的值。但是,它没有选择默认值(选中了inspect元素)。我在其他正常工作的地方使用类似的SelectLists代码。

以下是我的代码:

var techs = new HashSet<Guid>(db.usersInRoles.Where(u => u.RoleId == new Guid(Properties.Settings.Default.TechID)).Select(u => u.UserId));
ViewBag.TechnicianId = from user in db.Users
        join tech in techs on user.UserId equals tech
        where user.Status == 1
        orderby user.FirstName
        select new { TechnicianId = user.UserId, FullName = user.FirstName + " " + user.LastName };

和视图:

<span style="font-weight:normal;">@Html.DropDownListFor(m => m.TechnicianId, new SelectList(ViewBag.TechnicianId, "TechnicianId", "FullName"))</span>

找到此Question和此Question后,我将我的观点修改为:

<span style="font-weight:normal;">@Html.DropDownListFor(m => m.TechnicianId, new SelectList(ViewBag.TechnicianId, "TechnicianId", "FullName", @Model.TechnicianId))</span>

不幸的是,它仍未从模型中获取默认值。我不想改变我的模型来做一些应该如此简单的事情(如其中一个链接所示)。

这是正在运行的代码(对我来说是一样的):

ViewBag.Category = db.Categories.Where(c => c.Status == 1);

和视图:

<span style="font-weight:normal;">@Html.DropDownListFor(m =>
m.CategoryId, new SelectList(ViewBag.Category, "CategoryId", "CategoryName"))</span>

1 个答案:

答案 0 :(得分:0)

通常这样做是为了渲染下拉列表并选择项目作为选定选项。

public class CreateOrdeViewModel
{
    public List<SelectListItem> TechList {set;get;}
    public int SelectedTech {set;get;} 

    //Your other viewmodel properties also goes here
}

并且,在您的GET操作方法中:

public ActionResult Edit(int id)
{
    var vm = new CreateOrderViewModel();
    var order = dbContext.Orders.FirstOrDefault(s=>s.Id==id);

    vm.TechList = GetItems();
    //This is where you set the selected value which you read from db
    vm.SelectedTech = order.SelectedTechId;

    return View(vm);
}

private List<SelectListItem> GetItems()
{
    // just for demo. You may change the LINQ query to get your data. 
    // Just make sure to return a List<SelectListItem>
    return db.Users.Select(s => new SelectListItem   
    { 
        Value = s.Id.ToString(),
        Text = s.Name
    }).ToList();
}

并且,在您看来:

@model CreateOrderViewModel
@using(Html.BeginForm())
{
    @Html.DropDownListFor(s => s.SelectedTech, Model.TechList,"s")
}