无法在剃刀页面表单的选择列表中保存多个选择

Posted

技术标签:

【中文标题】无法在剃刀页面表单的选择列表中保存多个选择【英文标题】:Unable to save multiple selections in select lists in a razor page form 【发布时间】:2020-04-20 00:14:39 【问题描述】:

在这里我可以绑定多选选择列表。当我尝试保存时,我没有收到错误消息,但它没有保存官员信息。

这是尝试加载页面时的错误

处理请求时发生未处理的异常。 SqlException:列名“OfficerID”无效。 Microsoft.Data.SqlClient.SqlCommand+c.b__164_0(任务 结果)

Stack Query Cookies Headers Routing SqlException: Invalid column name “军官证”。 Microsoft.Data.SqlClient.SqlCommand+c.b__164_0(任务 结果) System.Threading.Tasks.ContinuationResultTaskFromResultTask.InnerInvoke() System.Threading.Tasks.Task+c.<.cctor>b__274_0(object obj) System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext、ContextCallback 回调、对象状态) System.Threading.Tasks.Task.ExecuteWithThreadLocal(参考任务 currentTaskSlot,线程线程池线程) Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject 参数对象,CancellationToken 取消令牌) Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject 参数对象,CancellationToken 取消令牌) Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject 参数对象,CancellationToken 取消令牌) Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable+AsyncEnumerator.InitializeReaderAsync(DbContext _, bool result, CancellationToken cancelToken) Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync(TState state, Func> operation, Func>> verifySucceeded, CancellationToken 取消令牌) Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable+AsyncEnumerator.MoveNextAsync() Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync(IQueryable 来源,CancellationToken 取消令牌) Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.ToListAsync(IQueryable 来源,CancellationToken 取消令牌) SecurityCore.PaginatedList.CreateAsync(IQueryable 源,int PageIndex, int pageSize) 在 PaginatedList.cs + var items = await source.Skip(SecurityCore.Pages.SecurityLogs.IndexModel.OnGetAsync(string sortOrder,字符串 currentFilter,字符串 searchString,Nullable index.cshtml.cs 中的 pageIndex,字符串 entitySelect) + SecurityLog = 等待 PaginatedList.CreateAsync(排序 Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory+NonGenericTaskHandlerMethod.Execute(对象 接收器,对象 [] 参数) Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync() Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync() Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext 语境) Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(参考 State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|24_0(ResourceInvoker 调用者,任务 lastTask,下一个状态,作用域范围,对象状态,布尔 完成了) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed 语境) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(参考状态 接下来,ref Scope 范围,ref 对象状态,ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|19_0(ResourceInvoker 调用者,任务 lastTask,下一个状态,作用域范围,对象状态,布尔 完成了) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Logged|17_1(ResourceInvoker 调用者) Microsoft.AspNetCore.Routing.EndpointMiddleware.g__AwaitRequestTask|6_0(端点 端点、任务 requestTask、ILogger 记录器) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext 语境) Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext 上下文)

这是我的代码...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using SecurityCore.Models;
using System.ComponentModel.DataAnnotations;

namespace SecurityCore.Pages.SecurityLogs

    public class IndexModel : PageModel
    
        private readonly SecurityCore.Models.SecurityCoreContext _context;

        public IndexModel(SecurityCore.Models.SecurityCoreContext context)
        
            _context = context;
        


        public string EventDateSort  get; set; 
        public string EventStartSort  get; set; 
        public string EventEndSort  get; set; 
        public string ContactNameSort  get; set; 
        public string EventTypeSort  get; set; 
        public string ShiftRangeSort  get; set; 
        public string EntitySort  get; set; 
        public string LocationSort  get; set; 
        public string NarrativeSort  get; set; 
        public string OfficerNameSort  get; set; 
        public string FullNameSort  get; set;             
        public string SubjectDOBSort  get; set; 
        public string RecordLockedSort  get; set; 
        public string CurrentFilter  get; set; 
        public string CurrentSort  get; set; 
        public string IDSort  get; set; 

        public Nullable<DateTime> dateEnd  get; set;       
        public Nullable<DateTime> dateBegin  get; set; 


        [TempData]
        public string Message  get; set; 

        public bool ShowMessage => !string.IsNullOrEmpty(Message);
        public PaginatedList<SecurityLog> SecurityLog  get; set;             


        public async Task OnGetAsync(string sortOrder, string currentFilter, string searchString, int? pageIndex, string entitySelect)
        

            ViewData["EntityID"] = new SelectList(_context.Entity.Where(a => a.Active == "Y"), "ID", "Name");

            CurrentSort = sortOrder;
            IDSort = sortOrder == "ID" ? "ID_Desc" : "ID";
            EventDateSort = sortOrder == "EventDate" ? "EventDate_Desc" : "EventDate";                
            ContactNameSort = sortOrder == "ContactName" ? "ContactName_Desc" : "ContactName";
            EventTypeSort = sortOrder == "EventType" ? "EventType_Desc" : "EventType";
            ShiftRangeSort = sortOrder == "ShiftRange" ? "ShiftRange_Desc" : "ShiftRange";
            EntitySort = sortOrder == "Entity" ? "Entity_Desc" : "Entity";
            LocationSort = sortOrder == "Location" ? "Location_Desc" : "Location";
            NarrativeSort = sortOrder == "Narrative" ? "Narrative_Desc" : "Narrative";
            FullNameSort = sortOrder == "FullName" ? "FullName_Desc" : "FullName";                
            RecordLockedSort = sortOrder == "Locked" ? "NotLocked" : "Locked";
            OfficerNameSort = sortOrder == "OfficerName" ? "OfficerName_Desc" : "OfficerName";

            if (searchString != null)
            
                pageIndex = 1;
            
            else
            
                searchString = currentFilter;
            

            CurrentFilter = searchString;


            IQueryable<SecurityCore.Models.SecurityLog> sort = from s in _context.SecurityLog select s;

            if (!String.IsNullOrEmpty(searchString))
            
                sort = sort.Where(s =>    s.Narrative.Contains(searchString)                                                                             
                                       || s.RecordLocked.Contains(searchString)
                                       || s.EventDate.ToString().Contains(searchString)                                                                                  
                                       || s.ContactName.Contains(searchString)
                                       || s.Entity.Name.Contains(searchString)
                                       || s.Location.Name.Contains(searchString)
                                       || s.EventType.Name.Contains(searchString)
                                       || s.ShiftRange.Name.Contains(searchString)
                                       || s.ID.ToString().Contains(searchString)
                                       || s.SubjectFirst.Contains(searchString)
                                       || s.SubjectLast.Contains(searchString)
                                       || s.Officer.FullName.Contains(searchString)                                           
                );
            

            switch (sortOrder)
            
                case "ID_Desc":
                    sort = sort.OrderByDescending(s => s.ID);
                    break;
                case "ID":
                    sort = sort.OrderBy(s => s.ID);
                    break;
                case "EventDate":
                    sort = sort.OrderBy(s => s.EventDate);                    
                    break;                
                case "ContactName":
                    sort = sort.OrderBy(s => s.ContactName).ThenBy(s => s.EventDate);
                    break;
                case "ContactName_Desc":
                    sort = sort.OrderByDescending(s => s.ContactName).ThenBy(s => s.EventDate);
                    break;
                case "ShiftRange":
                    sort = sort.OrderBy(s => s.ShiftRange.Name).ThenBy(s => s.EventDate);
                    break;
                case "ShiftRange_Desc":
                    sort = sort.OrderByDescending(s => s.ShiftRange.Name).ThenBy(s => s.EventDate);
                    break;
                case "EventType":
                    sort = sort.OrderBy(s => s.EventType.Name).ThenBy(s => s.EventDate);
                    break;
                case "EventType_Desc":
                    sort = sort.OrderByDescending(s => s.EventType.Name).ThenBy(s => s.EventDate);
                    break;
                case "Entity":
                    sort = sort.OrderBy(s => s.Entity.Name).ThenBy(s => s.EventDate);
                    break;
                case "Entity_Desc":
                    sort = sort.OrderByDescending(s => s.Entity.Name).ThenBy(s => s.EventDate);
                    break;
                case "Location":
                    sort = sort.OrderBy(s => s.Location.Name).ThenBy(s => s.EventDate);
                    break;
                case "Location_Desc":
                    sort = sort.OrderByDescending(s => s.Location.Name).ThenBy(s => s.EventDate);
                    break;
                case "Narrative":
                    sort = sort.OrderBy(s => s.Narrative).ThenBy(s => s.EventDate);
                    break;
                case "Narrative_Desc":
                    sort = sort.OrderByDescending(s => s.Narrative).ThenBy(s => s.EventDate);
                    break;                                    
                case "NotLocked":
                    sort = sort.OrderBy(s => s.RecordLocked).ThenBy(s => s.EventDate);
                    break;
                case "Locked":
                    sort = sort.OrderByDescending(s => s.RecordLocked).ThenBy(s => s.EventDate);
                    break;
                case "OfficerName":
                    sort = sort.OrderBy(s => s.Officer.FullName).ThenBy(s => s.EventDate);
                    break;
                case "OfficerName_Desc":
                    sort = sort.OrderByDescending(s => s.Officer.FullName).ThenBy(s => s.EventDate);
                    break;
                default:
                    sort = sort.OrderByDescending(s => s.EventDate);
                    break;
            

            int pageSize = 12;

            SecurityLog = await PaginatedList<SecurityLog>.CreateAsync(sort
                .Include(a => a.Entity)
                .Include(b => b.EventType)
                .Include(c => c.Location)
                .Include(d => d.ShiftRange)
                .Include(e => e.Officer)
                .Include(f => f.SecurityLogOfficer)                    
                .AsNoTracking(), pageIndex ?? 1, pageSize);           

               

    



//The Security Log Model

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using ExpressiveAnnotations.Attributes;

namespace SecurityCore.Models
   
    public class SecurityLog
            
        public int ID  get; set; 

        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "0:MM/dd/yyyy")]
        [Required]
        [Display(Name = "Event Date")]           
        public System.DateTime EventDate  get; set; 


        [Required]
        [Display(Name = "Shift Range")]       
        //[ForeignKey("ShiftRange")]
        public Nullable<int> ShiftRangeID  get; set; 

        [Required]
        //[ForeignKey("EventType")]
        [Display(Name = "Event Type")]
        public Nullable<int> EventTypeID  get; set; 

        [Required]
        [Display(Name = "Event Start")]
        [DataType(DataType.DateTime)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "0:MM/dd/yyyy  hh:mm")]
        public System.DateTime EventStart  get; set;             

        [Required]
        [Display(Name = "Event End")]
        [DataType(DataType.DateTime)]        
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "0:MM/dd/yyyy  hh:mm")]
        public System.DateTime EventEnd  get; set; 

        [Required]
        [Display(Name = "Reporting Person")]
        public string ContactName  get; set; 

        [Required]
        //[ForeignKey("Entity")]
        [Display(Name = "Entity")]
        public Nullable<int> EntityID  get; set; 

        [Required]
        //[ForeignKey("Location")]
        [Display(Name = "Location")]
        public Nullable<int> LocationID  get; set; 

        [Required]
        public string Narrative  get; set; 

        //Set length of narrative displayed
        private int NarrativeLimit = 200;
        [Display(Name = "Narrative")]
        public string NarrativeTrimmed
        
            get
            
                if (Narrative.Length > this.NarrativeLimit)
                    return this.Narrative.Substring(0, this.NarrativeLimit) + "...";
                else
                    return this.Narrative;
            
        

        [Required]
        [Display(Name = "Subject's First Name")]
        public string SubjectFirst  get; set; 

        [Required]
        [Display(Name = "Subject's Last Name")]
        public string SubjectLast  get; set; 


        [Display(Name = "Subject's Name")]
        public string FullName
        
            get
            
                return SubjectFirst + " " + SubjectLast;
                        
        

        [Display(Name = "Subject's B#/DOB")]
        public string SubjectDOB  get; set; 

        private string _RecordLocked;

        [Display(Name = "Record Locked?")]
        public string RecordLocked 
        
            get  return _RecordLocked; 
            set
            
                _RecordLocked = value;
                if (_RecordLocked == "Y")
                
                    try  
                    
                    catch(Exception ex)
                    

                    
                
                    
        


        [Display(Name = "Entered By")]
        public string EnteredBy  get; set; 

        [Display(Name = "Create Date")]
        [ReadOnly(true)]
        [DataType(DataType.Date)]
        public Nullable<System.DateTime> CreateDate  get; set; 

        [Display(Name = "Modified Date")]        
        [DataType(DataType.DateTime)]
        public Nullable<System.DateTime> ModifiedDate  get; set;                 

        [Display(Name = "Modified By")]
        public string ModifiedBy  get; set; 

        [Display(Name ="Number of Extinguishers")]        
        public Nullable<int> ExtinguisherNo  get; set; 

        [Display(Name ="Total Blankets")]
        public Nullable<int> BlanketNo  get; set; 

        [Display(Name ="Cause of Alarm")]
        public string FireAlarmCause  get; set; 

        [Display(Name ="Doors Closed in Area?")]
        public string DoorsClosed  get; set; 

        [Display(Name ="Number of Staff Responding")]
        public Nullable<int> StaffNo  get; set; 

        public virtual Entity Entity  get; set; 
        public virtual ShiftRange ShiftRange  get; set; 
        public virtual EventType EventType  get; set; 
        public virtual Location Location  get; set; 
        public virtual Officer Officer  get; set; 
        public virtual SecurityLogOfficer SecurityLogOfficer  get; set;         

    




//The Officer Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace SecurityCore.Models

    public class Officer
    
        [Required]
        public int ID  get; set; 

        //[Required]
        [Display(Name = "Officer's First Name")]
        public string FirstName  get; set; 

        //[Required]
        [Display(Name = "Officer's Last Name")]
        public string LastName  get; set; 

        [Display(Name = "Officer's Name")]
        public string FullName
        
            get
            
                return FirstName + " " + LastName;
            
        

        [Required]
        public string Active  get; set;             
        public string LoginName  get; set;      
        public virtual SecurityLogOfficer SecurityLogOfficer  get; set; 

    


//The SecurityLogOfficer Model

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace SecurityCore.Models

    public class SecurityLogOfficer
    
        [Required]
        public int ID  get; set; 

        [Required]
        public int SecurityLogID  get; set; 

        public int OfficerID  get; set;                  
    




//The Create Page that I am trying to post from…

using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using SecurityCore.Models;

namespace SecurityCore.Pages.SecurityLogs

    public class CreateModel : PageModel
    
        private readonly SecurityCore.Models.SecurityCoreContext _context;

        public CreateModel(SecurityCore.Models.SecurityCoreContext context)
        
            _context = context;
        

        public IActionResult OnGetAsync()
                      
            ViewData["EntityID"] = new SelectList(_context.Entity.Where(a=>a.Active == "Y"), "ID", "Name");
            ViewData["ShiftRangeID"] = new SelectList(_context.ShiftRange.Where(a=>a.Active == "Y"), "ID", "Name");
            ViewData["LocationID"] = new SelectList(_context.Location.Where(a=>a.Active == "Y"), "ID", "Name");
            ViewData["EventTypeID"] = new SelectList(_context.EventType.Where(a=>a.Active == "Y"), "ID","Name");
            ViewData["Officer"] = new SelectList(_context.Officer.Where(a => a.Active == "Y"), "ID", "FullName");

            return Page();
        

        [TempData]
        public string Message  get; set; 

        [BindProperty]
        public SecurityLog SecurityLog  get; set; 

        [BindProperty(SupportsGet = true)]
        public int entity  get; set; 
        public int eventType  get; set; 


        SelectList FilteredLocation;
        SelectList FilteredEventType;

        public JsonResult OnGetLocations()
        


            FilteredLocation = new SelectList(_context.Location.Where(c => c.EntityID == entity).Where(c =>c.Active == "Y").OrderBy(c =>c.Name), "ID", "Name");

            return new JsonResult(FilteredLocation);


        

        public JsonResult OnGetEventTypes()
        


            FilteredEventType = new SelectList(_context.EventType.Where(c => c.EntityID == entity).Where(c => c.Active == "Y").OrderBy(c => c.Name), "ID", "Name");

            return new JsonResult(FilteredEventType);     

                       


        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        public async Task<IActionResult> OnPostAsync()
        
            ModelState.Remove("EnteredBy");
            ModelState.Remove("ModifiedDate");
            ModelState.Remove("CreateDate");
            ModelState.Remove("ModifiedBy");
            ModelState.Remove("RecordLocked");


            if (!ModelState.IsValid)
            
                return Page();
            

            SecurityLog.EnteredBy = User.Identity.Name;
            SecurityLog.ModifiedDate = DateTime.Now;
            SecurityLog.CreateDate = DateTime.Now;
            SecurityLog.ModifiedBy = User.Identity.Name;
            SecurityLog.RecordLocked = "N";

            _context.SecurityLog.Add(SecurityLog);
            await _context.SaveChangesAsync();

            Message = "Entry added successfully!";

            return RedirectToPage("Index");

        



    

这是我的数据库架构和示例结果

任何帮助将不胜感激!

【问题讨论】:

您缺少列“Invalid column name 'OfficerID'”,请先修复它。 我在 SecurityLogOfficer 表和 SecurityLogOfficer 模型中都有这一列。其他地方需要吗? 【参考方案1】:

根据错误描述,Officer 表只有 ID 列。它没有OfficerID 列。尝试更改代码以反映 ID 列。

【讨论】:

我很困惑。属性OfficerID 仅在SecurityLogOfficer.cs 中声明。在 SecurityLog\Index 页面中,我引用了来自 Officer.cs 的 FullName 属性。这是通过公共虚拟官员获取访问的;放;财产。 更新 - 如果我将列“OfficerID”添加到 SecurityLog 表中,我不想这样做......错误消息消失了 securitylog 索引页面为同一事件,因为有 2 名安保人员分配给该事件。我怎样才能让安全人员在一列中显示逗号连接的人员列表? 我遇到的最大问题是我试图发布值并且在我的模型中没有直接的字段可以绑定。我看过一些使用 MVC 处理此问题的帖子,但没有看到任何没有控制器、动作和视图的示例。如何仅使用 asp.net Web 应用程序剃须刀页面做到这一点?

以上是关于无法在剃刀页面表单的选择列表中保存多个选择的主要内容,如果未能解决你的问题,请参考以下文章

无法保存表单的多个值[重复]

ie浏览器无法自动保存账号密码

从剃刀发布多阵列

在 Django 模型中保存时区

用户从图像列表中选择的 Python/Django 表单

一个页面上的多个表单