nii*_*ico 3 c# asp.net asp.net-mvc entity-framework asp.net-mvc-4
ASP.NET C#MVC 4 Code First应用程序 - 在Visual Studio 2012 Express,SQL Server 2012 Express中.
我有一个地方对象.我想在列表中输出所有地方的名称 - 每个地方旁边都有一个复选框.
然后我想登录用户选择他们喜欢的地方 - 并保存.然后,他们可以登录并再次查看它们,并选中相应的复选框.
什么是最好的方法?我是MVC的新手,并不确定这里的最佳实践.
谢谢
更新
下面的CheckboxListFor帮助程序工作得很好,但是如何处理用户选择并不明显(它只返回一个ID列表).
我创建了以下内容来获取ID列表 - 将其转换为对象列表,并将其添加到视图模型中的SelecteCities列表中.这将选择用户在发布页面之前选择的所有复选框:
public ActionResult Examples(PostedCities postedCities)
{
// ViewModel
CitiesViewModel cvm = new CitiesViewModel();
// Create list of cities
List<City> cities = new List<City>{
new City { Id = 1, Name = "London"},
new City { Id = 2, Name = "Saigon"},
new City { Id = 3, Name = "New York"}
};
// Assign list of cities to ViewModel
cvm.AvailableCities = cities;
// If posted cities present, user posted something (else probably first call)
if (postedCities.CityIDs != null)
{
// temporary city object
City cty = new City();
// List of selected cities
List<City> selCities = new List<City>();
// Go through each postedCity ID
foreach (string s in postedCities.CityIDs)
{
// Get ID of postedCity
int IdSel = Convert.ToInt32(s);
// Lookup city Id in cities
cty = cities.Single(c => c.Id == IdSel);
// Add selected city to cty object
selCities.Add(cty);
}
// Fill cvm.SelectedCities with selCities
cvm.SelectedCities = selCities;
}
return View(cvm);
}
Run Code Online (Sandbox Code Playgroud)
这是有效的 - 这是一个很好的方法还是我过于复杂?还是做得不好?
您可以保存自己的工作并使用现有的MvcCheckBoxList库.
使用以下命令使用nuget安装它:
PM> Install-Package MvcCheckBoxList
Run Code Online (Sandbox Code Playgroud)
这是他们的主页:MvcCheckBoxList
这里是文档:MvcCheckBoxList/Documentation
其他解决方案需要一些丑陋的编码.
更新
正如Klas Mellbourn建议的那样(我很抱歉将其视为理所当然),带有列表的视图模型将是此类场景的最佳实践.我提供的文档链接包含这些示例,供您更轻松地理解.
| 归档时间: |
|
| 查看次数: |
1571 次 |
| 最近记录: |