下面的代码在我的索引控制器操作中运行良好,该操作使用数据库数据填充下拉框。
我不想直接在我的控制器中使用它,因为我将在页面的多个位置使用下拉菜单。
var db = new StoreManagerEntities();
var query = db.Categories.Select(c => new
{
CategoryId = c.CategoryID,
Categoryname = c.CategoryName,
IsSelected = c.CategoryID.Equals(0)
});
var model = new SelectViewModel
{
List = query.ToList()
.Select(c => new SelectListItem
{
Value = c.CategoryId.ToString(),
Text = c.Categoryname,
Selected = c.IsSelected,
})
};
return View(model);
我希望能够将代码放在一个方法中并从我的控制器调用此方法 这是另一个我希望该方法使用的类。
public class NorthwindDataContext
{
StoreManagerEntities myDb = new StoreManagerEntities();
//retrieve all category objects
public List<Category> GetCategories()
{
return myDb.Categories.ToList();
}
//populate dropdownbox
public void PopulateDropdown()
{
var query = db.Categories.Select(c => new
{
CategoryId = c.CategoryID,
Categoryname = c.CategoryName,
IsSelected = c.CategoryID.Equals(0)
});
var model = new SelectViewModel
{
List = query.ToList()
.Select(c => new SelectListItem
{
Value = c.CategoryId.ToString(),
Text = c.Categoryname,
Selected = c.IsSelected,
})
};
}
}
Can you please show me how I can write the method here and have it
return the data I need back to the controller. It will be nice if you
can show me how to call this from the controller as well.