加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 如何使用asp.net mvc EditorTemplate

发布时间:2020-12-16 04:04:57 所属栏目:asp.Net 来源:网络整理
导读:我读到EditorTemplates是自动加载的,但是从asp.net mvc 2和现在3用剃刀,我仍然无法让它工作. 我的模型看起来像这样: public class RoleViewModel{ public int RoleId { get; set; } public bool InRole { get; set; } public string RoleName { get; set; }
我读到EditorTemplates是自动加载的,但是从asp.net mvc 2和现在3用剃刀,我仍然无法让它工作.

我的模型看起来像这样:

public class RoleViewModel
{
    public int RoleId { get; set; }
    public bool InRole { get; set; }
    public string RoleName { get; set; }
}

public class UserViewModel
{
    public User User { get; set; }
    public IEnumerable<RoleViewModel> Roles { get; set; }
}

我的观点如下:

?/查看/角色/ Edit.cshtml

@model Project.Web.ViewModel.UserViewModel
@using (Html.BeginForm()) {
   @Html.EditorFor(model => model.Roles)
   <!-- Other stuff here -->
}

?/查看/角色/ EditorTemplates / RoleViewModel.cshtml

@model Project.Web.ViewModel.RoleViewModel
@foreach (var i in Model)
{
    <div>
    @i.RoleName
    @Html.HiddenFor(model => i.RoleId)
    @Html.CheckBoxFor(model => i.InRole)
    </div>
}

如果我将内容从EditorTemplate移动到实际页面,那么它可以工作,它会显示复选框等.但是使用当前设置,显示的所有内容都是角色数量的计数.

我究竟做错了什么?

解决方法

?/查看/角色/ EditorTemplates / RoleViewModel.cshtml
@model MvcApplication16.Controllers.RoleViewModel
<div>
    @Model.RoleName
    @Html.HiddenFor(m => m.RoleId)
    @Html.CheckBoxFor(m => m.InRole)
</div>

?/查看/角色/ Edit.cshtml

@model MvcApplication16.Controllers.UserViewModel
@using (Html.BeginForm()) {
   @Html.EditorFor(m => m.Roles)
   <!-- Other stuff here -->
}

楷模

public class UserViewModel {
    public User User { get; set; }
    public IEnumerable<RoleViewModel> Roles { get; set; }
}

public class RoleViewModel {
    public int RoleId { get; set; }
    public bool InRole { get; set; }
    public string RoleName { get; set; }
}

public class User {
    public string Name { get; set; }
}

调节器

public ActionResult Edit() {
    return View(
        new UserViewModel() {
            User = new User() { Name = "Test" },Roles = new List<RoleViewModel>() { 
                new RoleViewModel() { 
                    RoleId = 1,InRole = true,RoleName = "Test Role" }}
        });
}

上面的代码工作得很好.与你的比较,看看你有没有看到任何问题:)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读