asp.net – CheckBoxList多个选择:难度模型绑定
发布时间:2020-05-24 22:56:44 所属栏目:asp.Net 来源:互联网
导读:我正在上课,如下 public class UserRoleModel{ public string Role { get; set; } public bool UserRole { get; set; }} 和public UserRoleModel [] UserRoles {get;组; } 我的控制器如下: public ActionResult CreateUser
|
我正在上课,如下 public class UserRoleModel
{
public string Role { get; set; }
public bool UserRole { get; set; }
}
和public UserRoleModel [] UserRoles {get;组; } 我的控制器如下: public ActionResult CreateUser()
{
UserDetailsModel model = new UserDetailsModel();
return View(model);
}
[HttpPost]
public ActionResult CreateUser(UserDetailsModel model)
{
return View(model);
}
在我看来我有 >@foreach (var item in Model.UserRoles)
{
name = "UserRoles"+ ".Value["+ i + "]";
id= "UserRoles" + "_Value[" + i++ + "]";
selected = item.UserRole ? "checked="checked"" : "";
<p>
<input type="checkbox" name="@name" id="@id" @selected value="true" />
<label for="@id">@item.Role</label>
<input type="hidden" name="@name" value="false" />
</p>
}
尽管我的看法中显示的值相应地显示,但是UserRoles没有模型绑定.我失踪了还是有更好更干净的方法? 解决方法使用编辑器模板很好地实现了这些事情.他们也避免你在你的意见中写意大利面条代码.例:模型: public class UserDetailsModel
{
public IEnumerable<UserRoleModel> Roles { get; set; }
}
public class UserRoleModel
{
public string Role { get; set; }
public bool UserRole { get; set; }
}
控制器: public class HomeController : Controller
{
public ActionResult Index()
{
return View(new UserDetailsModel
{
// Fill with some dummy stuff
Roles = Enumerable.Range(1,5).Select(x => new UserRoleModel
{
Role = "role " + x,UserRole = false
})
});
}
[HttpPost]
public ActionResult Index(UserDetailsModel model)
{
return View(model);
}
}
查看(/ Views / Home / Index.cshtml): @model AppName.Models.UserDetailsModel
@using (Html.BeginForm())
{
@Html.EditorFor(x => x.Roles)
<input type="submit" value="OK" />
}
编辑器模板(/ Views / Home / EditorTemplates / UserRoleModel.cshtml): @model AppName.Models.UserRoleModel @Html.CheckBoxFor(x => x.UserRole) @Html.LabelFor(x => x.Role,Model.Role) @Html.HiddenFor(x => x.Role) 现在这就是我所说的干净的东西. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-membership – 使用SQL提供程序获取ASP.NET成员资格
- 如何最小化ASP.NET C#项目DLL大小?
- asp.net – 从单独的配置文件中读取设置
- VS 2015.为ASP.NET 5 web项目设置正确的目标框架
- 在ASP.NET应用程序中托管的WCF服务中使用Autofac作为DI
- asp.net – 在Azure网站上启用gzip压缩
- ASP.NET:文字属性中的单引号和双引号
- asp.net-mvc – Validator.TryValidateObject不验证RangeAt
- asp.net-core – 如何注入对特定IHostedService实现的引用?
- asp.net mvc调试器抛出SEHException
推荐文章
站长推荐
- asp.net-mvc – WebApi是否支持开箱即用的applic
- 如何用Asp.net中的javascript检测IE 11
- asp.net-mvc – Asp.net Identity使用什么算法来
- asp.net-mvc-3 – Editor用于收集我的模型中的项
- 依赖于文件的.net核心asp.net单元测试 – appset
- 使用ASP.Net MVC与经典ADO.Net
- asp.net-mvc – MVC区域 – 非区域路线解析为区域
- 如何在ASP.NET项目中正确引用JavaScript文件?
- 有没有办法远程调用ASP.NET开发Web服务器?
- asp.net – FF和IE不从CSS加载img src
热点阅读
