不存在具有键“List”的“IEnumerable<SelectListItem>”类型的 ViewData 项

不存在具有键“List”的“IEnumerable”类型的 ViewData 项
Controllers中,
//加载数据库,下拉列表
public ActionResult ADDBUMEN()
{
//ViewBag.List = “”;
//var list = db.Department.Select(x => new { x.DepId, x.DepManageId, x.DepName, x.Depnumber }).ToList();
//return Json(list, JsonRequestBehavior.AllowGet);

        var list = db.Department.AsNoTracking().ToList().Select(x => new SelectListItem { Text = x.DepId.ToString(), Value = x.Depnumber }).ToList();
        SelectList sellist = new SelectList(list, "DepId", "Depnumber");
        ViewData["List"] = list;
        return View();
    }
    View中
    <p class="lead">@Html.DropDownList("List",  "请选择")</p>
    大神们这个怎么回事啊
An unhandled exception occurred while processing the request. SqlNullValueException: Data is Null. This method or property cannot be called on Null values. Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull() Stack Query Cookies Headers Routing SqlNullValueException: Data is Null. This method or property cannot be called on Null values. Microsoft.Data.SqlClient.SqlBuffer.ThrowIfNull() Microsoft.Data.SqlClient.SqlBuffer.get_Int32() Microsoft.Data.SqlClient.SqlDataReader.GetInt32(int i) lambda_method372(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator ) Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable<T>+Enumerator.MoveNext() Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetListItemsWithValueField() Microsoft.AspNetCore.Mvc.Rendering.MultiSelectList.GetEnumerator() System.Collections.Generic.List<T>..ctor(IEnumerable<T> collection) System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source) Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateGroupsAndOptions(string optionLabel, IEnumerable<SelectListItem> selectList, ICollection<string> currentValues) Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateSelect(ViewContext viewContext, ModelExplorer modelExplorer, string optionLabel, string expression, IEnumerable<SelectListItem> selectList, ICollection<string> currentValues, bool allowMultiple, object htmlAttributes) Microsoft.AspNetCore.Mvc.TagHelpers.SelectTagHelper.Process(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext) AspNetCoreGeneratedDocument.Views_People_Create.<ExecuteAsync>b__20_0() Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder) Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count) AspNetCoreGeneratedDocument.Views_People_Create.ExecuteAsync() in Create.cshtml + Layout = "~/Views/Shared/_Layout.cshtml"; Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts) Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ActionContext actionContext, IView view, ViewDataDictionary viewData, ITempDataDictionary tempData, string contentType, Nullable<int> statusCode) Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result) Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) Program+<>c+<<<Main>$>b__0_3>d.MoveNext() in Program.cs + await next(); Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context) Show raw exception details
最新发布
10-09
<think>好的,我现在需要解决用户的问题:如何将`IEnumerable<CompletionItem>`类型安全地转换为`IEnumerable<string>`。首先,我得理解这两个类型之间的关系以及转换的可能方法。 用户提到的类型是泛型的IEnumerable,所以可能需要使用LINQ的Select方法进行投影。比如,如果每个CompletionItem有一个属性是string类型的,比如Text,那么可以通过Select(c => c.Text)来转换。这样转换后的结果就是IEnumerable<string>,因为LINQ的Select方法会返回一个延迟执行的查询,类型也是正确的。 过,我需要考虑类型安全的问题。如果CompletionItem没有相应的string属性,或者某些元素可能为null,这时候转换可能会出错。因此,在转换之前需要确保每个CompletionItem都有有效的string属性,或者在转换过程中进行过滤或处理null值的情况。 另外,用户可能需要处理集合中的空引用。例如,使用Where(c => c != null)来过滤掉可能为空的CompletionItem,或者在转换时使用空条件运算符,比如c?.Text,然后配合Where(t => t != null)来确保最终的字符串集合没有空值。 还要注意转换后的类型是否真的是IEnumerable<string>。如果直接使用Cast<string>()方法的话,这要求CompletionItem必须能够显式转换为string,否则会在运行时抛出异常。所以这种方法可能太安全,推荐使用Select进行属性投影更可靠。 另外,引用中的内容提到IEnumerable<T>是只读的,只能前向迭代,所以在转换后的集合也是可修改的,用户需要注意这一点。如果需要修改集合,可能需要转换为List<string>或者其他可变的集合类型。 总结下来,可能的步骤是: 1. 确定CompletionItem中需要转换为string的属性或方法。 2. 使用Select方法进行投影,比如.Select(c => c.Text)。 3. 处理可能的null值,使用Where过滤或者在投影时处理。 4. 避免使用Cast方法,除非确保类型兼容性。 5. 考虑是否需要立即执行转换,比如使用ToList()来具体化结果。 现在需要验证这些思路是否正确。比如,如果CompletionItem有一个Name属性是string,那么转换应该是直接的。如果用户的环境中有可能某些元素为null,或者属性存在,就需要异常处理或者过滤。同时,考虑到类型安全,使用Select投影是类型安全的方法,而Cast可能安全。 最后,注意事包括确保源集合的有效性,处理null,以及延迟执行特性。这些都需要在回答中提及,确保用户了解潜在的问题和解决方案。</think>### 类型安全转换方法及步骤 #### 方法1:使用`Select`进行属性映射(推荐) 若`CompletionItem`包含字符串属性(如`Text`或`Name`),可通过LINQ的`Select`方法直接提取: ```csharp IEnumerable<CompletionItem> completionItems = GetCompletionItems(); IEnumerable<string> strings = completionItems.Select(item => item.Text); ``` - **注意事**: 1. 若`Text`属性可能为`null`,可添加过滤: ```csharp IEnumerable<string> strings = completionItems .Where(item => item.Text != null) .Select(item => item.Text); ``` 2. 若属性名称同(如`DisplayName`),需按实际字段名调整[^3]。 --- #### 方法2:显式类型转换(需确保类型兼容) 若`CompletionItem`本身可隐式转换为`string`(如重写了`ToString()`方法): ```csharp IEnumerable<string> strings = completionItems .Select(item => item.ToString()); ``` - **注意事**: 1. 需验证`ToString()`返回值是否符合预期,否则需自定义转换逻辑。 --- #### 方法3:使用`Cast`方法(推荐,需严格类型匹配) 仅当`CompletionItem`继承自`string`时可用(罕见场景): ```csharp IEnumerable<string> strings = completionItems.Cast<string>(); ``` - **风险**:若类型匹配,会抛出`InvalidCastException`[^2]。 --- ### 注意事总结 1. **延迟执行特性**:转换后的`IEnumerable<string>`仍是延迟执行,多次迭代可能重复计算。 2. **空值处理**:通过`Where`或空值合并运算符(`??`)避免空引用异常: ```csharp IEnumerable<string> strings = completionItems .Select(item => item.Text ?? string.Empty); ``` 3. **性能优化**:若需频繁访问结果,可调用`.ToList()`或`.ToArray()`具体化集合: ```csharp List<string> stringList = completionItems.Select(item => item.Text).ToList(); ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值