【问题标题】:how I can bind my datasource to view?如何将我的数据源绑定到视图?
【发布时间】:2011-07-18 05:58:09
【问题描述】:

我有一个严重的问题,我无法在表单提交时将我的数据传递给控制器​​,我该如何解决这个问题?

//int controller class
[HttpPost]
public ActionResult Index(EnterpriseFramework.Entity.Synchronization.BindableEntity model)
{
    //do something
}

我的看法:

@model EnterpriseFramework.Entity.Synchronization.BindableEntity 

<p>
    @using (Html.BeginForm())
    {
        <fieldset>
            <legend>title</legend>
            <div>
                @Html.HiddenFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Id)
            </div>
            <div>                
                @Html.LabelFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Number)
                @Html.TextBoxFor(m => (m.Underlay.Entity as AutomationTest.Models.DTO.Letter).oau_Letter_Number)
            </div>
            <div>
                @{
                    EnterpriseFramework.Entity.Synchronization.DataSource ds = Model.GetRelation("lnkLetterReceiver");
                    foreach (EnterpriseFramework.Entity.Synchronization.BindableEntity  item in ds)
                    {
                        AutomationTest.Models.DTO.LetterReceiver childRece = item.Underlay.Entity as 
                            AutomationTest.Models.DTO.LetterReceiver;
                        <div>                            
                            @Html.LabelFor(c=> childRece.oau_LetterReceiver_Name)
                            @Html.TextBoxFor(c=> childRece.oau_LetterReceiver_Name)
                        </div>
                    }
                }              
            </div>
            <div>
                <input type="submit" name="Confirm" value="Confirm" />
            </div>
        </fieldset>
    }
</p>

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.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +199
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +572
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +449
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +317
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
   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() +8897857
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

【问题讨论】:

  • 我有亲子关系

标签: asp.net-mvc model-view-controller asp.net-mvc-3


【解决方案1】:

您尝试用作操作参数的每种类型都必须具有默认的无参数构造函数。否则默认模型绑定器将无法实例化它并填充其属性。

这就是为什么你永远不应该在视图中使用你的领域模型。您应该定义和使用视图模型,它们是专门为满足给定视图的要求而设计的类。然后控制器动作将在视图模型和域模型之间来回映射。像这样:

[HttpPost]
public ActionResult Index(MyViewModel model)
{  
    if (!ModelState.IsValid)
    {
        // There were validation errors => redisplay the view
        return View(model);
    }

    // the model is valid => map the view model to a domain model and process 
    ...
}

就最佳做法而言。如果您的应用程序已经被污染并且目前无法重构视图模型,那么您有两种可能性:

  1. 为 BindableEntity 类型编写自定义模型绑定器,以便您在 CreateModel 方法中手动调用正确的构造函数。
  2. BindableEntity 类型添加一个默认的无参数构造函数。
  3. 使用TryUpdateModel 方法:

    [HttpPost]
    public ActionResult Index()
    {  
        var model = new BindableEntity(WHATEVER);
        if (!TryUpdateModel(model) || !ModelState.IsValid)
        {
            // There were validation errors => redisplay the view
            return View(model);
        }
    
        // the model is valid => process 
        ...
    }
    

【讨论】:

  • 我得到数据,我需要按用户保存更改。
  • 当我将 [httppost] 添加到 index() 无参数时,资源无法显示
【解决方案2】:

我假设你只定义了带参数的构造函数?要解决这个问题,你需要添加这行代码

public BindableEntity()
{ }

致您的EnterpriseFramework.Entity.Synchronization.BindableEntity 班级。

这将定义一个无参数构造函数,并允许您根据需要使用它,尽管您确实需要定义一个 ViewModel 以便按照设计的方式使用 MVC。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-28
    • 2013-07-17
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多