在MVC中通过一个List
在MVC中通过一个List
我有一个模型:
public class DbUserRole { public int UserRoleId { get; set; } public string UserRole { get; set; } } public class DbUserRoles { public ListGetRoles() { BugnetReports RoleDropDown = new BugnetReports(); List Roles = new List (); DataSet table = RoleDropDown.userRoleDropDown(); foreach (DataRow item in table.Tables[0].Rows) { DbUserRole ur = new DbUserRole(); ur.UserRole = Convert.ToString(item["UserRoleName"]); ur.UserRoleId = Convert.ToInt32(item["UserRoleID"]); Roles.Add(ur); } return Roles; } }
这是加载视图的控制器:
// // GET: /Admin/AddNewUser public ActionResult AddNewUser() { DbUserRoles Roles = new DbUserRoles(); return View(Roles.GetRoles()); }
我可以使用@foreach
循环来显示列表中的项目,如下所示:
@foreach (var item in Model) {} @item.UserRoleId @item.UserRole
但是,我如何使用传递的模型填充下拉列表?我尝试过
@Html.DropDownListFor(x => x.UserRole)
但是没有成功。
问题:从一个List
原因:
问题1:为什么在DropDownList方法中使用Model.Select()时会报错"Model doesn't have a Select"?
问题2:为什么需要使用System.Linq命名空间中的Select扩展方法?
解决方法:
问题1的解决方法:原因是Model没有Select方法,可以通过引入System.Linq命名空间中的Select扩展方法来解决该问题。
问题2的解决方法:在使用DropDownList方法时,通过Model.Select()方法来为下拉列表填充数据。在这个例子中,通过遍历List
完整代码如下所示:
@Html.DropDownList("ddl", Model.Select(item => new SelectListItem { Value = item.RecordID.ToString(), Text = item.Name.ToString(), Selected = "select" == item.RecordID.ToString() }))
为了使用Select方法,需要在代码中引入System.Linq命名空间,代码如下所示:
using System.Linq;
以上就是关于从一个List
问题的出现原因:需要在MVC中从一个List
解决方法:
1. 创建一个ViewModel,用于存储用户选择的Id以及将出现在下拉列表中的项目的列表。
2. 在控制器中创建一个方法来获取UserRoles列表,并将其转换为在视图中呈现的形式。
3. 创建一个View来呈现下拉列表。
在MVC中,有时候需要从一个List
首先,我们可以将业务逻辑分离到一个ViewModel中,这样视图就能更清晰地分离出来。我们可以创建一个ViewModel来存储用户选择的Id以及将出现在下拉列表中的项目的列表。
public class UserRoleViewModel { [Display(Name = "User Role")] public int SelectedUserRoleId { get; set; } public IEnumerableUserRoles { get; set; } }
在控制器中,我们可以创建一个方法来获取UserRoles列表,并将其转换为在视图中呈现的形式。
private IEnumerableGetRoles() { var dbUserRoles = new DbUserRoles(); var roles = dbUserRoles .GetRoles() .Select(x => new SelectListItem { Value = x.UserRoleId.ToString(), Text = x.UserRole }); return new SelectList(roles, "Value", "Text"); } public ActionResult AddNewUser() { var model = new UserRoleViewModel { UserRoles = GetRoles() }; return View(model); }
现在,我们已经创建了ViewModel,呈现逻辑也变得更简单了。
在视图中,我们可以直接使用ViewModel来呈现下拉列表。
@model UserRoleViewModel @Html.LabelFor(m => m.SelectedUserRoleId) @Html.DropDownListFor(m => m.SelectedUserRoleId, Model.UserRoles)
通过以上的代码,我们可以生成以下的HTML代码:
以上就是从一个List
问题的原因:在MVC中,有时需要从一个包含对象的列表中填充下拉列表。然而,通过简单地在视图中循环遍历列表并将每个对象的属性添加为下拉列表选项是不够的。这可能导致无法正确填充下拉列表或无法获得想要的结果。
解决方法:一个解决方法是使用Razor语法在视图中手动创建下拉列表,并从列表中的对象填充选项。可以使用如下代码来实现:
这样,通过循环遍历列表中的每个对象,可以将每个对象的属性添加为下拉列表的选项。在这个例子中,我们假设列表中的每个对象有一个UserRoleId属性和一个UserRole属性。通过使用`@`符号将C#代码嵌入到Razor视图中,可以动态地将属性的值添加到对应的选项中。
使用这种方法,可以完全控制生成的HTML,并确保下拉列表被正确地填充。这种方法也可以应用于其他需要从列表中填充下拉列表的情况。
以上是一种在MVC中从List