微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net-mvc – ASP.NET MVC – 用于ICollection的EditorTemplate映射到Enum的问题

我有一个ASP.NET MVC 3(Razor)网站和一个名为Review的(简化)模型:
public class Review
{
   public int ReviewId { get; set; }
   public bool RecommendationOne
   {
       // hook property - gets/set values in the ICollection
   }
   public bool RecommendationTwo { // etc }
   public ICollection<Recommendation> Recommendations { get; set; }
}

建议如下:

public class Recommendation
{
   public byte RecommendationTypeId
}

我还有一个名为RecommendationType的枚举,用于将上述建议映射到. (基于RecommendationTypeId).

总而言之 – 单个Review有很多Recommendations,并且每个Recommendations都映射到特定的枚举类型,我公开了钩子属性以简化模型绑定/代码.

所以,在视图上:

@Html.EditorFor(model => model.Recommendations,"Recommendations")

很简单.

现在,对于编辑器模板,我想显示每个可能的RecommendationType(枚举)的复选框,如果模型有该推荐(例如编辑视图),我选中该复选框.

这就是我所拥有的:

@model IEnumerable<xxxx.DomainModel.Core.Posts.Recommendation>
@using xxxx.DomainModel.Core.Posts;

@{
    Layout = null;
}

<table>
    @foreach (var rec in Enum.GetValues(typeof(RecommendationType)).Cast<RecommendationType>())
    {
        <tr>
            <td>
                @* If review contains this recommendation,check the Box *@
                @if (Model != null && Model.Any(x => x.RecommendationTypeId == (byte)rec))
                {
                    @* How do i create a (checked) checkBox here? *@
                }
                else
                {
                    @* How do i created a checkBox here? *@
                }

                @rec.ToDescription()
            </td>
        </tr>
    }
</table>

正如评论所示 – 我不知道如何使用@ Html.CheckBoxFor.通常,它采用基于模型的表达式,但我更确定如何基于当前循环的枚举值绑定到hook属性.例如,它需要动态地执行@ Html.CheckBoxFor(x => x.RecommendationOne),@ Html.CheckBoxFor(x => x.RecommendationTwo)等.

我现有的解决方案(有效)涉及手动构建< input>. (包括隐藏的字段).

但是,由于我只是掌握了编辑器模板,希望有经验的人可以指出我处于“强烈打字”的方向.

或者有更好的方式(HTML Helper)我能做到这一点吗?

解决方法

我首先介绍一个适用于该场景的视图模型:
public enum RecommendationType { One,Two,Three }

public class Reviewviewmodel
{
    public IEnumerable<Recommendationviewmodel> Recommendations { get; set; }
}

public class Recommendationviewmodel
{
    public RecommendationType RecommendationType { get; set; }
    public bool IsChecked { get; set; }
}

然后是控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        // Todo: query the repository to fetch your model
        // and use AutoMapper to map between it and the 
        // corresponding view model so that you have a true/false
        // for each enum value
        var model = new Reviewviewmodel
        {
            Recommendations = new[]
            {
                new Recommendationviewmodel { 
                    RecommendationType = RecommendationType.One,IsChecked = false 
                },new Recommendationviewmodel { 
                    RecommendationType = RecommendationType.Two,IsChecked = true 
                },new Recommendationviewmodel { 
                    RecommendationType = RecommendationType.Three,}
        };
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(Reviewviewmodel model)
    {
        // Here you will get for each enum value the corresponding
        // checked value
        // Todo: Use AutoMapper to map back to your model and persist
        // using a repository
        return RedirectToAction("Success");
    }
}

和相应的视图(〜/ Views / Home / Index.cshtml):

@model YourAppName.Models.Reviewviewmodel

@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm())
{
    @Html.EditorFor(model => model.Recommendations)
    <input type="submit" value="Go" />
}

最后是编辑模板(〜/ Views / Home / EditorTemplates / Recommendationviewmodel.cshtml)

@model YourAppName.Models.Recommendationviewmodel
<div>
    @Html.HiddenFor(x => x.RecommendationType)
    @Model.RecommendationType 
    @Html.CheckBoxFor(x => x.IsChecked)
</div>

现在,视图代码将按原样清理.没有ifs,没有循环,没有LINQ,没有反射,这是控制器/映射器层的责任.因此,每当您发现自己在视图中编写一些高级C#逻辑时,我建议您重新考虑视图模型并根据需要进行调整.这就是视图模型的用途:尽可能接近视图逻辑.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“WPF...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这...
Some samples are below for ASP.Net web form controls:(from http://www.visualize.uk.com/resources/asp
问题描述: 对于未定义为 System.String 的列,唯一有效的值是(引发异常)。 For columns not defined as System.String, the only vali
最近用到了CalendarExtender,结果不知道为什么发生了错位,如图在Google和百度上找了很久,中文的文章里面似乎只提到了如何本地化(就是显示中文的月份)以及怎么解决被下拉框挡住的问题,谈
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence changed a lot since 1.1. Here is the order: App
静态声明: &#39; Style=&quot;position: relative&quot; AppendDataBoundItems=&quot;True&quot;&gt; (无 或 空 或
以下内容是从网络上搜集资料,然后整理而来的。不当之处,请不吝指教。(The following were from network, and edited by myself. Thanks in a
Imports System Imports System.Reflection Namespace DotNetNuke &#39;*********************************
Ok so you have all seen them: “8 million tools for web development”, “5 gagillion tools that if you