ASP.NET MVC - Problem with EditorTemplate for ICollection<T> mapped to Enum

荒凉一梦 提交于 2019-11-29 07:39:52

I would start by introducing a proper view model for the scenario:

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; }
}

Then the controller:

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, 
                    IsChecked = true 
                },
            }
        };
        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");
    }
}

and the corresponding view (~/Views/Home/Index.cshtml):

@model YourAppName.Models.ReviewViewModel

@{
    ViewBag.Title = "Index";
}

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

and finally the editor template (~/Views/Home/EditorTemplates/RecommendationViewModel.cshtml)

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

Now the view code is cleaned as it should. No ifs, no loops, no LINQ, no reflection, this is the responsibility of the controller/mapper layer. So every time you find yourself writing some advanced C# logic in your view I would recommend you rethinking your view models and adapt them as necessary. That's what view models are intended for: to be as close as possible to the view logic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!