C# &引用;“干涸”;使用SelectListItem时的MVC模型

C# &引用;“干涸”;使用SelectListItem时的MVC模型,c#,asp.net,asp.net-mvc,asp.net-mvc-5,dry,C#,Asp.net,Asp.net Mvc,Asp.net Mvc 5,Dry,我刚刚开始使用MVC,我能够在网上找到大多数枯燥原则的例子。虽然我没有全部使用,因为我发现有些代码会使代码更难阅读 我找到了一个我找不到的例子,但我觉得一定有办法做到这一点 基本上,目前我在控制器中填充ModelSelectList类型的对象,这意味着我必须重用代码。我知道我可以把它放在一个方法中,但我想知道是否还有其他方法可以把它放在模型中,以便在使用模型/视图模型时调用此操作来填充selectlist内容 我在下面给出了一个代码示例 型号 查看 创建 @使用(Html.BeginForm()

我刚刚开始使用MVC,我能够在网上找到大多数枯燥原则的例子。虽然我没有全部使用,因为我发现有些代码会使代码更难阅读

我找到了一个我找不到的例子,但我觉得一定有办法做到这一点

基本上,目前我在控制器中填充ModelSelectList类型的对象,这意味着我必须重用代码。我知道我可以把它放在一个方法中,但我想知道是否还有其他方法可以把它放在模型中,以便在使用模型/视图模型时调用此操作来填充selectlist内容

我在下面给出了一个代码示例

型号

查看

创建
@使用(Html.BeginForm())
{
@Html.AntiForgeryToken()
定制网站

@Html.ValidationSummary(true,“,new{@class=“text danger”}) @if(User.IsInRole(“管理员”)) { @LabelFor(model=>model.UserGuid,htmlAttributes:new{@class=“controllabel col-md-2”}) @Html.DropDownListFor(model=>model.UserGuid,model.AllUsers,“--选择一个用户--”) @Html.ValidationMessageFor(model=>model.UserGuid,“,new{@class=“text danger”}) } @LabelFor(model=>model.WebsiteAddress,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.WebsiteAddress,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.WebsiteAddress,“,new{@class=“text danger”}) @LabelFor(model=>model.WebsiteType,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.WebsiteType,new{htmlAttributes=new{@class=“form control”}}) @Html.ValidationMessageFor(model=>model.WebsiteType,“,new{@class=“text danger”}) @LabelFor(model=>model.ReleaseDate,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.ReleaseDate,new{htmlAttributes=new{@class=“form control”}}) @Html.ValidationMessageFor(model=>model.ReleaseDate,“,new{@class=“text danger”}) @LabelFor(model=>model.Description,htmlAttributes:new{@class=“controllabel col-md-2”}) @Html.TextAreaFor(model=>model.Description,新的{rows=“10”,@class=“form control”}) @Html.ValidationMessageFor(model=>model.Description,“,new{@class=“text danger”}) @if(User.IsInRole(“管理员”)) { @LabelFor(model=>model.DevelopmentStatus,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.DevelopmentStatus,new{htmlAttributes=new{@class=“form control”}}) @Html.ValidationMessageFor(model=>model.DevelopmentStatus,“,new{@class=“text danger”}) @LabelFor(model=>model.CompletedPercentage,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.CompletedPercentage,new{htmlAttributes=new{@class=“form control”}}) @Html.ValidationMessageFor(model=>model.CompletedPercentage,“,new{@class=“text danger”}) @LabelFor(model=>model.Completed,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Completed) @Html.ValidationMessageFor(model=>model.Completed,“,new{@class=“text danger”}) @LabelFor(model=>model.TotalCost,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.TotalCost,new{htmlAttributes=new{@class=“form control”}}) @Html.ValidationMessageFor(model=>model.TotalCost,“,new{@class=“text danger”}) @LabelFor(model=>model.TotalPaid,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.TotalPaid,new{htmlAttributes=new{@class=“form control”}}) @Html.ValidationMessageFor(model=>model.TotalPaid,“,new{@class=“text danger”}) } @LabelFor(model=>model.Budget,htmlAttributes:new{@class=“controllabel col-md-2”}) @EditorFor(model=>model.Budget,new{htmlAttributes=new{@class=“form control”}) @Html.ValidationMessageFor(model=>model.Budget,“,new{@class=“text danger”}) }
基本上目前我在中填充模型selectlist类型对象 控制器,这意味着我必须重用代码。我知道我可以 只是把它放在一个方法中,但我想知道是否还有其他方法可以放 它在模型中显示,以便在使用模型/视图模型时 调用操作以填充selectlist内容

在viewmodels中放置任何方法通常都不是一个好主意,尤其是对于数据访问和填充。视图模型应该是简单的数据容器,没有知识或行为。Y
using System;
using System.Data.Entity;

namespace MyWebsite.Models
{
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    namespace CustomerWebsites.Models
    {
        public class CustomerWebsites
        {
            public int Id { get; set; }
            public Guid UserGuid { get; set; }
            public string WebsiteAddress { get; set; }
            public string WebsiteType { get; set; }
            public DateTime ReleaseDate { get; set; }
            public string Description { get; set; }
            public decimal Budget { get; set; }
            public DateTime CreationDate { get; set; }
            public string DevelopmentStatus { get; set; }
            public int CompletedPercentage { get; set; }
            public bool Completed { get; set; }
            public decimal TotalCost { get; set; }
            public decimal TotalPaid { get; set; }

        }

        public class CustomerWebsitesDBContext : DbContext
        {
            public CustomerWebsitesDBContext()
            : base("DefaultConnection")
        {
        }

            public static CustomerWebsitesDBContext Create()
            {
                return new CustomerWebsitesDBContext();
            }
            public DbSet<CustomerWebsites> CustomerWebsites { get; set; }
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace MyWebsite.ViewModels
{
    public class CreateCustomerWebsites
    {
        public int Id { get; set; }
        public Guid UserGuid { get; set; }

        [Required]
        public string WebsiteAddress { get; set; }
        public string WebsiteType { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Description { get; set; }
        public decimal Budget { get; set; }
        public DateTime CreationDate { get; set; }
        public string DevelopmentStatus { get; set; }
        public int CompletedPercentage { get; set; }
        public bool Completed { get; set; }
        public decimal TotalCost { get; set; }
        public decimal TotalPaid { get; set; }
        public IEnumerable<SelectListItem> AllUsers { get; set; }

    }

}
// GET: CustomerWebsites/Create

        public ActionResult Create()
        {
            var db = new ApplicationDbContext();
            var users = db.Users.ToArray();

            var allUsers = users.Select(x => new SelectListItem
            {
                Value = x.Id,
                Text = x.Email
            });
            var model = new CreateCustomerWebsites
            {
                AllUsers = allUsers
            };

           return View(model);
        }

        // POST: CustomerWebsites/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(CreateCustomerWebsites model)
        {
            if (ModelState.IsValid)
            {
                var userGuid = new Guid(User.Identity.GetUserId());
                var developmentStatus = "Pending MyWebsite Review";

                if (User.IsInRole("Administrator"))
                {
                    userGuid = model.UserGuid;
                    developmentStatus = model.DevelopmentStatus;
                } 


                db.CustomerWebsites.Add(new CustomerWebsites
                {
                    UserGuid = userGuid,
                    WebsiteAddress = model.WebsiteAddress,
                    CreationDate = DateTime.Now,
                    ReleaseDate = model.ReleaseDate,
                    Budget = model.Budget ,
                    Description = model.Description,
                    DevelopmentStatus = developmentStatus,
                    CompletedPercentage = model.CompletedPercentage,
                    Completed = model.Completed,
                    TotalCost = model.TotalCost,
                    TotalPaid = model.TotalPaid
                });
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            var dbUsers = new ApplicationDbContext();
            var users = dbUsers.Users.ToArray();

            var allUsers = users.Select(x => new SelectListItem
            {
                Value = x.Id,
                Text = x.Email
            });
            model = new CreateCustomerWebsites
            {
                AllUsers = allUsers
            };
            return View(model);
        }
<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>CustomerWebsites</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @if (User.IsInRole("Administrator"))
        {
        <div class="form-group">
            @Html.LabelFor(model => model.UserGuid, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.UserGuid, Model.AllUsers, "-- Select a user --")
                @Html.ValidationMessageFor(model => model.UserGuid, "", new { @class = "text-danger" })
            </div>
        </div>
       }

        <div class="form-group">
            @Html.LabelFor(model => model.WebsiteAddress, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.WebsiteAddress, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.WebsiteAddress, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.WebsiteType, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.WebsiteType, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.WebsiteType, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ReleaseDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ReleaseDate, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ReleaseDate, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.Description, new { rows = "10", @class = "form-control"  })
                @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
            </div>
        </div>

        @if (User.IsInRole("Administrator"))
        {
            <div class="form-group">
                @Html.LabelFor(model => model.DevelopmentStatus, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.DevelopmentStatus, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.DevelopmentStatus, "", new {@class = "text-danger"})
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.CompletedPercentage, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.CompletedPercentage, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.CompletedPercentage, "", new {@class = "text-danger"})
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Completed, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    <div class="checkbox">
                        @Html.EditorFor(model => model.Completed)
                        @Html.ValidationMessageFor(model => model.Completed, "", new {@class = "text-danger"})
                    </div>
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.TotalCost, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.TotalCost, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.TotalCost, "", new {@class = "text-danger"})
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.TotalPaid, htmlAttributes: new {@class = "control-label col-md-2"})
                <div class="col-md-10">
                    @Html.EditorFor(model => model.TotalPaid, new {htmlAttributes = new {@class = "form-control"}})
                    @Html.ValidationMessageFor(model => model.TotalPaid, "", new {@class = "text-danger"})
                </div>
            </div>
        }
        <div class="form-group">
            @Html.LabelFor(model => model.Budget, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Budget, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Budget, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}
var users = dbUsers.Users.ToArray();
model = new CreateCustomerWebsites
{
    AllUsers = Mapper.Map<IEnumerable<SelectListItem>>(users)
};
public SelectList GetAsSelectList()
{
    var b = CacheHelper.GetCacheItem("UserSelectList", UsersDelegate, CacheHelper.SlidingParam, CacheHelper.AbsoluteParam);
    return new SelectList((IEnumerable)b, "Id", "Name");
 }
private object UsersDelegate()
{
     return (from c in _context.Set<Users>()
             select new
             {
                c.Id, c.Name
             }).ToList();
}