以下代码在我的索引控制器操作中运行良好 使用数据库数据填充下拉框。
我不想直接在我的控制器中使用它,因为我将使用它 我页面上多个位置的下拉列表。
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.
答案 0 :(得分:0)
如何更改NorthwindDataContext
类
public class NorthwindDataContext
{
StoreManagerEntities myDb = new StoreManagerEntities();
//retrieve all category objects
public List<Category> GetCategories()
{
return myDb.Categories.ToList();
}
//populate dropdownbox
public SelectViewModel 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,
})
};
return model;
}
}
请注意PopulateDropdown()
和return model;
并在控制器中使用它,如:
var db = new NorthwindDataContext();
var model = db.PopulateDropdown();
return View(model);