2010-05-08 4 views
0

asp.net mvc 2.0 (기본 바인딩 모델)을 사용하고 있는데이 문제가 있습니다.복잡한 클래스에 드롭 다운 목록 데이터를 바인딩하는 방법?

나는이 이제 드롭 다운리스트

<%= Html.DropDownList("List", "-----")%> 

을 가지고 강력하게 형식화 된 뷰를 가지고 나는이

public ActionResult TestAction() 
    { 
     Test ViewModel = new Test(); 
     ViewModel.List = new SelectList(GetList(), "value", "text", "selected"); 
     return View(Test); 
    } 

    [AcceptVerbs(HttpVerbs.Post)] 
    public ActionResult TestAction(Test ViewModel) 
    { 
      return View(); 
    } 

지금 내 컨트롤러에있는 지금

Public class Test 
{ 
    public List { get; set; } 
    public string Selected {get; set;} 

    public Test() 
    { 
      List = new List(); 
      selected = ""; 
    } 
} 

같은 모델 클래스 처음으로 TestAction 페이지를로드하면 예상대로 드롭 다운 목록이 채워집니다.

이제 선택한 값을 다시 서버에 게시하려고합니다 (드롭 다운 목록은 다른 텍스트 상자가있는 양식 태그 내에 있음). 그래서 (Test ViewModel)

그러나 나는이 큰 고약한 오류가 나타납니다 때 자동으로 바인딩하려고합니다.

Server Error in '/' Application. 
No parameterless constructor defined for this object. 
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.MissingMethodException: No parameterless constructor defined for this object. 

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. 

Stack Trace: 

[MissingMethodException: No parameterless constructor defined for this object.] 
    System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 
    System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98 
    System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241 
    System.Activator.CreateInstance(Type type, Boolean nonPublic) +69 
    System.Activator.CreateInstance(Type type) +6 
    System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +403 
    System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +544 
    System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +479 
    System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +45 
    System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +658 
    System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +147 
    System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +98 
    System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +2504 
    System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +548 
    System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +474 
    System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +181 
    System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 
    System.Web.Mvc.Controller.ExecuteCore() +136 
    System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111 
    System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39 
    System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +65 
    System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +44 
    System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +42 
    System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52 
    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8836913 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184 

어떻게하면됩니까?

답변

1

당신이 강력한 형식의 도우미와 함께하려고 생각 했습니까?

I 카테고리 선택을위한 다수의 드롭 다운 내보기 비슷한 일을하고 나는 다음과 같은 코드를 사용하고

: 당신은 그것을 시도 할 수

<%= Html.DropDownListFor(model => model.Selected, Model.List) %> 

을 ..

그리고 왜 뒤에 괄호를해야합니까 public class Test (필자의 경우 유효한 문법이 아님)

Public class Test() <- 
{ 
    public List { get; set; } 
    public string Selected {get; set;} 
} 
+0

죄송합니다. 늦게까지이 게시물을 작성했습니다. 거기 있으면 안된다. 처음으로 그것이 문제가되는 것은 페이지의 생성이 아니라 포스트 백입니다. – chobo2

+0

흠 나는 For와 함께 linq 방법을 시도하고 그것은 작동하는 것 같습니다. 그러나 나는 그것이 어떻게 작동하는지에 관해 안다. 그러나 그것은 일한다!. 나는 또한 당신이 linq을 조금 다른 식으로 소스와 별도로해야만한다는 것이 이상하다는 것을 알았다. – chobo2

+0

'Model.List'를 사용하면 List 값을 가져 와서'model => model.Selected'를 통해 모델의 Selected 속성에 적용합니다. –

0

반사 코드에서 모델 개체에 매개 변수없는 생성자가 필요합니다. Test 클래스에 클래스가 없습니다.

이 잘 작동해야합니다

Public class Test() 
{ 
    public Test() 
    { 
     this.List = new List(); 
     this.Selected = string.Empty; 
    } 

    public List { get; set; } 
    public string Selected {get; set;} 
} 
+0

생성해야하는 자동 기본값이 있어야합니다. 어쨌든 나는 그것을 시도했지만 여전히 효과가 없습니다. – chobo2

0

감사합니다. 이제 마법처럼

<%= Html.DropDownListFor(model => model.Selected, Model.List) %> 

작품, 내가 이유를 파악하는 시간을 (그가 처음에 대해 게시 된와 오뎃은 ... 당신의 "더 나은 솔루션"같은 오류를 제공).