Asp.net mvc 4 Mvc:Create方法从类和控制器调用填充下拉列表
下面的代码在我的索引控制器操作中运行得非常好 它使用数据库数据填充下拉框 我不想在我的控制器中直接使用它,因为我将使用 下拉列表在我的页面的多个位置Asp.net mvc 4 Mvc:Create方法从类和控制器调用填充下拉列表,asp.net-mvc-4,Asp.net Mvc 4,下面的代码在我的索引控制器操作中运行得非常好 它使用数据库数据填充下拉框 我不想在我的控制器中直接使用它,因为我将使用 下拉列表在我的页面的多个位置 var db = new StoreManagerEntities(); var query = db.Categories.Select(c => new { CategoryId = c.CategoryID, Categoryname = c.Categor
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.
公共类NorthwindDataContext
{
StoreManagerEntities myDb=新的StoreManagerEntities();
//检索所有类别对象
公共列表GetCategories()
{
返回myDb.Categories.ToList();
}
//填充下拉框
public void PopulateDropdown()
{
var query=db.Categories.Select(c=>new
{
CategoryId=c.CategoryId,
Categoryname=c.Categoryname,
IsSelected=c.CategoryID.等于(0)
});
var模型=新建SelectViewModel
{
List=query.ToList()
.选择(c=>new SelectListItem
{
Value=c.CategoryId.ToString(),
Text=c.类别名称,
选择=c.IsSelected,
})
};
}
}
你能告诉我怎么在这里写这个方法吗
将我需要的数据返回控制器。如果你愿意,那就太好了
你也可以告诉我如何从控制器调用它。
如何更改您的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;
}
}
你的问题是?你能告诉我如何在类中编写这个方法,并让它将我需要的数据返回给控制器吗。如果你能告诉我如何从控制器调用它,那就太好了。
var db = new NorthwindDataContext();
var model = db.PopulateDropdown();
return View(model);