2016-07-05 58 views
1

定義在ASP.NET核心RC 1(完整的.NET框架)的作品對我下面的代碼:ModelStateDictionary不包含CopyTo從

using System.Collections.Generic; 
using System.Linq; 
using Microsoft.AspNet.Mvc; 
using Microsoft.AspNet.Mvc.Filters; 
using Microsoft.AspNet.Mvc.ModelBinding; 
using Newtonsoft.Json; 

namespace MyProject.Classes.Filters.ModelState 
{ 
    public class SetTempDataModelStateAttribute : ActionFilterAttribute 
    { 
     public override void OnActionExecuted(ActionExecutedContext filterContext) 
     { 
      base.OnActionExecuted(filterContext); 

      var controller = filterContext.Controller as Controller; 
      if (controller != null) 
      { 
       var modelState = controller.ViewData.ModelState; 
       if (modelState != null) 
       { 
        var dictionary = new KeyValuePair<string, ModelStateEntry>[modelState.Count]; 
        modelState.CopyTo(dictionary, 0); 
        var listError = dictionary.ToDictionary(m => m.Key, m => m.Value.Errors.Select(s => s.ErrorMessage).FirstOrDefault(s => s != null)); 
        controller.TempData["ModelState"] = JsonConvert.SerializeObject(listError); 
       } 
      } 
     } 
    } 
} 

但在ASP.NET 1.0的核心(完整的.NET框架),發生錯誤:

using System.Collections.Generic; 
using System.Linq; 
using Microsoft.AspNetCore.Mvc; 
using Microsoft.AspNetCore.Mvc.Filters; 
using Microsoft.AspNetCore.Mvc.ModelBinding; 
using Newtonsoft.Json; 

namespace MyProject.Models.ModelState 
{ 
    public class SetTempDataModelStateAttribute : ActionFilterAttribute 
    { 
     public override void OnActionExecuted(ActionExecutedContext filterContext) 
     { 
      base.OnActionExecuted(filterContext); 

      var controller = filterContext.Controller as Controller; 
      if (controller != null) 
      { 
       var modelState = controller.ViewData.ModelState; 
       if (modelState != null) 
       { 
        var dictionary = new KeyValuePair<string, ModelStateEntry>[modelState.Count]; 
        modelState.CopyTo(dictionary, 0); 
        modelState = dictionary.[0]; 
        var listError = dictionary.ToDictionary(m => m.Key, m => m.Value.Errors.Select(s => s.ErrorMessage).FirstOrDefault(s => s != null)); 
        controller.TempData["ModelState"] = JsonConvert.SerializeObject(listError); 
       } 
      } 
     } 
    } 
} 

「ModelStateDictionary」不包含一個定義爲「CopyTo從」和 沒有擴展方法「CopyTo從」接受 類型的第一參數「ModelStateDictionary」可以b Ë(是否缺少using 指令或程序集引用?)

也許我需要一個新的參考連接到未在ASP.NET核心RC 1需要的組件?

+0

也許添加'System.Web'可以解決錯誤。 –

+0

@diiN_不,添加'System.Web'沒有解決問題 –

+1

請不要使用ASP.NET MVC相關問題的'asp.net-mvc6'標籤來避免混淆未來的ASP.NET MVC版本。也不要將標籤填入問題標題 – Tseng

回答

1

ModelStateDictionary不執行IDictionary<,>因此沒有一個CopyTo方法。在你的情況,你可以用

var listErrorr = modelState.ToDictionary(
    m => m.Key, 
    m => m.Value.Errors 
    .Select(s => s.ErrorMessage) 
    .FirstOrDefault(s => s != null) 
); 

更換你的代碼,並應在功能上等同於你在原來的片段在做什麼。