2011-03-23 1 views
0

제약 :모델 클래스의 인스턴스가 뷰에 전달되지 않을 때 Create.cshtml의 EditorFor (x = x.Prop)에서 생성 된 null 예외를 방지하는 방법은 무엇입니까?

  1. 나는 Nullable 유형을 사용하지 않습니다.
  2. HttpGet -handling Create 조치 메소드에서 모델 클래스를 인스턴스화하고 싶지 않습니다.

모델 클래스 :

namespace MvcTest.Models 
{ 
    public enum Gender { Male, Female } 
    public class Person 
    { 
     public Gender Gender { get; set; } 
    } 
} 

템플릿 기반 편집기 도우미 (Gender.cshtml)

@using MvcTest.Models 
@model Gender 
@{ 
    var genders = from Gender g in Enum.GetValues(typeof(Gender)) 
        select new { Value = g, Text = g.ToString() }; 

    var sl = new SelectList(genders, "Value", "Text", Model); 
} 
@Html.DropDownList(string.Empty, sl, "--Select--") 

컨트롤러 :

using System.Web.Mvc; 
using MvcTest.Models; 

namespace MvcTest.Controllers 
{ 
    public class HomeController : Controller 
    { 
     public ActionResult Create() 
     { 
      //Person p = new Person(); 
      //return View(p); 

      return View(); 
     } 

    } 
} 

보기 :

@model MvcTest.Models.Person 
@using (Html.BeginForm()) 
{ 

    @Html.EditorFor(x => x.Gender) 
    <p> 
     <input type="submit" value="Create" /> 
    </p> 
} 

오류 :

Server Error in '/' Application. 

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'MvcTest.Models.Gender'. 

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.InvalidOperationException: The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'MvcTest.Models.Gender'. 

Source Error: 


Line 3: { 
Line 4:  
Line 5:  @Html.EditorFor(x => x.Gender) 
Line 6:  <p> 
Line 7:   <input type="submit" value="Create" /> 

Source File: e:\MvcTest\MvcTest\Views\Home\Create.cshtml Line: 5 

Stack Trace: 


[InvalidOperationException: The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'MvcTest.Models.Gender'.] 
    System.Web.Mvc.ViewDataDictionary`1.SetModel(Object value) +143 
    System.Web.Mvc.ViewDataDictionary..ctor(ViewDataDictionary dictionary) +377 
    System.Web.Mvc.WebViewPage`1.SetViewData(ViewDataDictionary viewData) +27 
    System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +99 
    System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115 
    System.Web.Mvc.Html.TemplateHelpers.ExecuteTemplate(HtmlHelper html, ViewDataDictionary viewData, String templateName, DataBoundControlMode mode, GetViewNamesDelegate getViewNames, GetDefaultActionsDelegate getDefaultActions) +584 
    System.Web.Mvc.Html.TemplateHelpers.TemplateHelper(HtmlHelper html, ModelMetadata metadata, String htmlFieldName, String templateName, DataBoundControlMode mode, Object additionalViewData, ExecuteTemplateDelegate executeTemplate) +1027 
    System.Web.Mvc.Html.TemplateHelpers.TemplateHelper(HtmlHelper html, ModelMetadata metadata, String htmlFieldName, String templateName, DataBoundControlMode mode, Object additionalViewData) +66 
    System.Web.Mvc.Html.TemplateHelpers.TemplateFor(HtmlHelper`1 html, Expression`1 expression, String templateName, String htmlFieldName, DataBoundControlMode mode, Object additionalViewData, TemplateHelperDelegate templateHelper) +118 
    System.Web.Mvc.Html.TemplateHelpers.TemplateFor(HtmlHelper`1 html, Expression`1 expression, String templateName, String htmlFieldName, DataBoundControlMode mode, Object additionalViewData) +100 
    System.Web.Mvc.Html.EditorExtensions.EditorFor(HtmlHelper`1 html, Expression`1 expression) +57 
    ASP._Page_Views_Home_Create_cshtml.Execute() in e:\MvcTest\MvcTest\Views\Home\Create.cshtml:5 
    System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207 
    System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +81 
    System.Web.WebPages.StartPage.RunPage() +19 
    System.Web.WebPages.StartPage.ExecutePageHierarchy() +65 
    System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76 
    System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +220 
    System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115 
    System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +303 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13 
    System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +23 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +260 
    System.Web.Mvc.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b() +19 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +177 
    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343 
    System.Web.Mvc.Controller.ExecuteCore() +116 
    System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97 
    System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10 
    System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37 
    System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21 
    System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12 
    System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62 
    System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50 
    System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7 
    System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22 
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60 
    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862381 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225 

질문 : Create.cshtml 때의 EditorFor (X = x.Prop)에 의해 생성 된 널 (null) 예외를 방지하는 방법 모델 클래스의 인스턴스가 뷰에 전달되지 않습니까?

+0

두 번째 요구 사항은 모범 사례와 절대 모순이 있으며보기 모델에서 강력한 형식의보기가 있습니다. –

+0

@Darin : 드롭 다운 컨트롤에 기본적으로'--Select -'가 채워지고'Male' 또는'Female'으로 채워지지 않기를 바래. – LaTeX

+0

@Darin : 나는 포기합니다, 나는 nullable enum을 사용해야합니다 : D – LaTeX

답변

2

AFAIK이 작업을 수행하려면 nullable enum을 사용해야합니다. 또한 값이 선택되지 않으면 (--SELECT--) 열거 형이 null이어야하기 때문에 의미가 있습니다. 유용한 확장 방법에 대한 설명은 nice blog post입니다.

+0

@Darin : 편집기 템플릿이'Edit' 액션 메소드에 대해 작동할까요? 나는이 질문을하기 전에 이미 그것을 시도했다. 드롭 다운 컨트롤은'Edit.cshtml'에서'--Select -'입니다. 드롭 다운 목록 컨트롤은 성별 속성을 반영하지 않습니다. – LaTeX

+0

@Administrator, 정확합니다. 내 초기 답변은 편집 작업에 대해 작동하지 않으며 모델을 기반으로 드롭 다운 목록에서 올바른 값을 미리 선택하지 않습니다. 찾은 솔루션은 작동해야하지만 의미 상으로이 시나리오에서 더 정확하므로 nullable enum을 사용합니다. –

+0

@ 다린 : 내 업데이트를 확인하십시오. @ Branislav의'와 결합하여 이전 솔루션을 사용 했습니까? :'연산자. – LaTeX

관련 문제