代码之家  ›  专栏  ›  技术社区  ›  Syntax Error ine

在post方法中初始化新列表时,下拉列表为空

  •  -1
  • Syntax Error ine  · 技术社区  · 6 年前

    我的控制器中有以下内容:

    using System.Collections.Generic;
    using System.Configuration;
    using System.Data.Entity;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Net;
    using System.Web.Mvc;
    using ContactReport_MVC.Models;
    
    namespace ContactReport_MVC.Controllers
    {
        public class ReportsController : Controller
        {
            private ReportDBContext db = new ReportDBContext();
    
            // GET: Reports
            public ActionResult Index()
            {
                return View(db.Reports.ToList());
            }
    
            // GET: Reports/Details/5
            public ActionResult Details(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Report report = db.Reports.Find(id);
                if (report == null)
                {
                    return HttpNotFound();
                }
                return View(report);
            }
    
            // GET: Reports/Create
            public ActionResult Create()
            {
                var model = new Report();
                model.ContactsList = GetContacts();
                return View(model);
            }
    
            // POST: Reports/Create
            // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
            // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Create(Report report)
            {
                if (ModelState.IsValid)
                {
                    db.Reports.Add(report);
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                var model = new Report();
                return View(model);
            }
    
            // GET: Reports/Edit/5
            public ActionResult Edit(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Report report = db.Reports.Find(id);
                if (report == null)
                {
                    return HttpNotFound();
                }
                return View(report);
            }
    
            // POST: Reports/Edit/5
            // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
            // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
            [HttpPost]
            [ValidateAntiForgeryToken]
            public ActionResult Edit([Bind(Include = "Id,Contacts,MeetingDate,SubmittedBy,ClientType,Location,ContactName,Purpose,Discussed,Actions")] Report report)
            {
                if (ModelState.IsValid)
                {
                    db.Entry(report).State = EntityState.Modified;
                    db.SaveChanges();
                    return RedirectToAction("Index");
                }
                return View(report);
            }
    
            // GET: Reports/Delete/5
            public ActionResult Delete(int? id)
            {
                if (id == null)
                {
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
                }
                Report report = db.Reports.Find(id);
                if (report == null)
                {
                    return HttpNotFound();
                }
                return View(report);
            }
    
            // POST: Reports/Delete/5
            [HttpPost, ActionName("Delete")]
            [ValidateAntiForgeryToken]
            public ActionResult DeleteConfirmed(int id)
            {
                Report report = db.Reports.Find(id);
                db.Reports.Remove(report);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
    
            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }
    
            private static List<SelectListItem> GetContacts()
            {
                List<SelectListItem> items = new List<SelectListItem>();
                string constr = ConfigurationManager.ConnectionStrings["650sContactReportConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    string query = @"SELECT  TOP 1000   e.DisplayEmployeeId as [Id], EmployeeDescNoID as [Name]
                                    FROM [Cascade].[dbo].[Employee] e
                                    join [Cascade].[dbo].[EmployeeJobs] ej on e.employeeid = ej.EmployeeId
                                    Where
                                    (e.leftdate is null 
                                    and ej.sys_ActiveJob = 1)
                                    order by surname asc";
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            while (sdr.Read())
                            {
                                items.Add(new SelectListItem
                                {
                                    Text = sdr["Name"].ToString(),
                                    Value = sdr["Id"].ToString()
                                });
                            }
                        }
                        con.Close();
                    }
                }
    
                return items;
            }
        }
    }
    

    如果我尝试使用此(at/reports/create)发布表单,则会得到以下错误:

    System.InvalidOperationException:“没有类型为”IEnumerable“且具有键”contacts“的ViewData项。”

    我可以把它放进控制器来解决这个问题: report.ContactsList = new List<SelectListItem>(); 但是我的下拉列表显示为空。

    我的HTML助手如下所示:

    @Html.DropDownListFor(model => model.Contacts, Model.ContactsList, new { @class = "form-control js-data", @multiple = "multiple", @placeholder = "Type here to search, press enter or tab to select" })
    

    我想我在问如何从控制器传递填充列表 Create 方法,进入 Post 方法,以便将其提交到数据库。

    另外,如何将列表的值(多选下拉列表)存储到模型中定义的字符串字段中 Contacts ?

    型号代码:

     public class Report
     {
            public int Id { get; set; }
    
            [Required]
            [Display(Name = "Relevant Contacts")]
            public string Contacts { get; set; }
    
            [Required]
            [Display(Name = "Date of meeting")]
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
            public DateTime MeetingDate { get; set; }
    
            [Required]
            public string CompanyName { get; set; }
            [Display(Name = "Submitted By")]
    
            public string SubmittedBy { get; set; }
    
            [Required]
            [Display(Name = "Client Type")]
            public string ClientType { get; set; }
    
            [Required]
            [Display(Name = "Location of meeting")]
            public string Location { get; set; }
    
            [Required]
            [Display(Name = "Client Contact(s)")]
            public string ContactName { get; set; }
    
            [Required]
            [Display(Name = "Purpose of meeting")]
            public string Purpose { get; set; }
    
            [AllowHtml]
            [Required]
            [Display(Name = "What was discussed")]
            [Column(TypeName = "varchar(MAX)")]
            public string Discussed { get; set; }
    
            [AllowHtml]
            [Required]
            [Display(Name = "Actions to take")]
            [Column(TypeName = "varchar(MAX)")]
            public string Actions { get; set; }
    
            [NotMapped]
            public IEnumerable<SelectListItem> ContactsList { get; set; }
    
    }
    
    public class ReportDBContext : DbContext 
    {
            public DbSet<Report> Reports  { get; set; }
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Antoine V    6 年前

    您的视图需要一个联系人列表来填充组合框。你可以把它放在模型里 Report 但这是一个糟糕的设计。

    为了不污染模型,可以创建 CreateReportViewModel

    public class Report
    {
        public string Contacts { get; set; }
        //other property
    }
    
    public class CreateReportViewModel {
        [Required]
        [Display(Name = "Relevant Contacts")]
        public string Contacts { get; set; }
    
        public IEnumerable<SelectListItem> ContactsList { get; set; }
    }
    

    接下来,您可以通过自己或第三方将模型映射到视图模型。( AutoMapper 即)。在控制器中,填充视图所需的信息

    public ActionResult Create()
    {
         var reportModel = new CreateReportViewModel();
         //init ContactsList
         reportModel.ContactsList = GetContacts(); //this method retrieves a   list from a database table
    }
    [HttpPost]
    public ActionResult Create(CreateReportViewModel reportModel)
    {
        if (ModelState.IsValid)
        {
            var report = new Report();
            report.Contacts = reportModel.Contacts;
            //save to db
        }
        else
        {          
            return View(reportModel);
        }
    
    }