默认模型绑定抛出“没有为此对象定义无参数构造函数”

2024-01-01

我有一个表格,我们想在其中为单个客户输入多个交易。表单的视图模型如下所示:

public class TradeSpendingEntryViewModel
{
    public TradeSpendingEntryViewModel()
    {
        Records = new List<TradeSpendingEntryViewModelRecord>();
    }

    public string CustomerNumber { get; set; }
    public DateTime Date { get; set; }
    public SelectList PlanningYears { get; set; }

    public List<TradeSpendingEntryViewModelRecord> Records { get; set; }
}

我们希望能够使用 JavaScript 动态添加和删除记录条目行。集合中的每条记录是:

public class TradeSpendingEntryViewModelRecord
{
    public TradeSpendingEntryViewModelRecord()
    {
    }

    public string LOB { get; set; }
    public string ProductCode { get; set; }
    public SelectList AllowType { get; set; }
    public int Cases { get; set; }
    public bool EndCurrentDeal { get; set; }
    public Single DealRate { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public string Comments { get; set; }
}

当我尝试将数据发布到控制器时,出现错误,指示“没有为此对象定义无参数构造函数:

[HttpPost]
    public ActionResult Index(TradeSpendingEntryViewModel vm)
    {
        try
        {
            if (ModelState.IsValid)
            {
                return RedirectToAction("Index");
            }
            // TODO: Add insert logic here
            return View(vm);
        }
        catch
        {
            return View();
        }
    }

堆栈跟踪表明它发生在模型绑定期间:

[MissingMethodException:没有为此对象定义无参数构造函数。] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(布尔publicOnly,布尔skipCheckThis,布尔fillCache,StackCrawlMark&stackMark)+113 System.RuntimeType.CreateInstanceDefaultCtor(布尔publicOnly,布尔skipCheckThis,布尔fillCache,StackCrawlMark&stackMark)+232 System.Activator.CreateInstance(类型类型,布尔非公共)+83 System.Activator.CreateInstance(类型类型) +6 System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContextcontrollerContext,ModelBindingContext绑定Context,类型modelType)+183

我的问题一定源于我如何设置视图,其标记是基于本文的http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx

@using (Html.BeginForm())
{
<header class="clearfix">
        <img src="../../Content/images/logo.png" alt="Irving Consumer Products" />
        <h1>Enter Customer Deals</h1>
    </header>
    <hr />
    <fieldset>
        <legend>Customer details</legend>
        <table>
            <tr>
                <th>
                    Date:
                </th>
                <td>
                    <input type="date" disabled="disabled" value="@DateTime.Today.ToShortDateString()" />
            </tr>
            <tr>
                <th>
                    Customer Number:
                </th>
                <td>
                    @Html.TextBoxFor(m => m.CustomerNumber, new { id = "customer-number" })
                    <a href="#" id="change-customer-number">Change me</a>
                </td>
            </tr>
            <tr>
                <th>
                    Customer Name:
                </th>
                <td>
                    <input type="text" id="customer-name" disabled="disabled" />
                </td>
                <tr>
                    <th>
                        Planning Year:
                    </th>
                    <td>
                        @Html.DropDownList("PlanningYear", Model.PlanningYears)
                        <a href="#" id="change-planning-year">Change me</a>
                    </td>
                </tr>
        </table>
    </fieldset>
    <div class="buttonGroup">
        <input type="button" value="Add line" id="add-line">
        <input type="button" value="Copy line" id="copy-line">
        <input type="button" value="Delete line" id="delete-line">
    </div>
    <hr />
    <table id="tradeSpendingEntry">
        <thead>
            <tr>
                <th>
                </th>
                <th>
                    Line of business
                </th>
                <th>
                    Product Code
                </th>
                <th>
                    Product Description
                </th>
                <th>
                    Allowance
                    <br />
                    Type
                </th>
                <th>
                    Cases
                </th>
                <th>
                    End Current Deal
                </th>
                <th>
                    Start Date
                </th>
                <th>
                    End Date
                </th>
                <th>
                    Rate
                </th>
            </tr>
        </thead>
        @foreach (var r in Model.Records)
        {
            <tbody data-entry-index="0">
            <tr>
                <td>
                    <input type="checkbox" />
                </td>
                <td>
                    <input type="text" name="records[0].LOB" class="lobSelect" value="@r.LOB">
                </td>
                <td>
                    <!--<input type="hidden" name="records[0]ProductCodeSelected" value="@r.ProductCode" />-->
                    <input type="text" name="records[0].ProductCode" value="@r.ProductCode">
                </td>
                <td>
                    <input type="text" class="product-description" disabled="disabled" />
                </td>
                <td>
                    @Html.DropDownList("records[0].AllowType", r.AllowType)
                </td>
                <td>
                    <input name="records[0].Cases" type="number" />
                </td>
                <td>
                    <select name="records[0].EndCurrentDeal">
                        <option value="true" selected="selected">Yes</option>
                        <option value="false">No</option>
                    </select>
                </td>
                <td>
                    <input type="date" name="records[0].StartDate" />
                </td>
                <td>
                    <input type="date" name="records[0].EndDate" />
                </td>
                <td>
                    <input type="text" name="records[0].DealRate" />
                </td>
                </tr>
            <tr>
                <td></td>
                <td>
                    Comments:
                </td>
                <td colspan="8">
                    <input type="text" class="comment" name="records[0].Comments" />
                </td>
                </tr>
        </tbody>
        }
    </table>

    <footer>
        <div class="buttonGroup">
        <input type="submit" value="Submit Changes">
        <input type="button" value="Main Menu">
        <input type="button" value="View Customer Deals">
    </div>
    </footer>
    }

因此,我希望第一个字段集中的字段能够映射到 TradeSpendingEntryViewModel 对象的直接属性(CustomerName、Date、PlanningYears)。然后,对于每个代表 TradeSpendingEntryViewModelRecord 的对象,将被绑定为 TradeSpendingEntryViewModel.Records 集合中的一项。相反,我只是得到一个神秘的“未定义无参数构造函数”异常,尽管 ViewModel 和记录对象都具有无参数构造函数。

我的问题是,我可以使用上述文章中指出的约定使用默认模型绑定程序,还是需要为此目的构建自定义模型绑定程序?

为了完整起见,以下是用户通过 javascript 向表单动态添加一行后生成的表单标记:

<form method="post" action="/TradeSpendingEntry/Index">
<header class="clearfix">
<img alt="Irving Consumer Products" src="../../Content/images/logo.png">
<h1>Enter Customer Deals</h1>
</header>
<hr>
<fieldset>
<legend>Customer details</legend>
<table>
<tbody>
<tr>
<th> Date: </th>
<td>
<input id="dp1363608756704" class="hasDatepicker" type="date" value="18/03/2013" disabled="disabled" style="background-color: rgb(238, 238, 238);">
</td>
</tr>
<tr>
<th> Customer Number: </th>
<td>
<input id="customer-number" type="text" value="" name="CustomerNumber">
<a id="change-customer-number" href="#">Change me</a>
</td>
</tr>
<tr>
<th> Customer Name: </th>
<td>
<input id="customer-name" type="text" disabled="disabled" style="background-color: rgb(238, 238, 238);">
</td>
</tr>
<tr>
<th> Planning Year: </th>
<td>
<select id="PlanningYears" name="PlanningYears">
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
<option value="2014">2014</option>
</select>
<a id="change-planning-year" href="#">Change me</a>
</td>
</tr>
</tbody>
</table>
</fieldset>
<div class="buttonGroup">
<input id="add-line" type="button" value="Add line">
<input id="copy-line" type="button" value="Copy line">
<input id="delete-line" type="button" value="Delete line">
</div>
<hr>
<table id="tradeSpendingEntry">
<thead>
<tr>
<th> </th>
<th> Line of business </th>
<th> Product Code </th>
<th> Product Description </th>
<th>
Allowance
<br>
Type
</th>
<th> Cases </th>
<th> End Current Deal </th>
<th> Start Date </th>
<th> End Date </th>
<th> Rate </th>
</tr>
</thead>
<tbody data-entry-index="0">
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input class="lobSelect" type="text" name="records[0].LOB">
</td>
<td>
<input type="text" name="records[0].ProductCode">
</td>
<td>
<input class="product-description" type="text" disabled="disabled" style="background-color: rgb(238, 238, 238);">
</td>
<td>
<select id="records_0__AllowType" name="records[0].AllowType">
<option selected="selected">BillBack$</option>
<option>Billback%</option>
<option>O&A%</option>
<option>Coop%</option>
<option>VR%</option>
<option>Lump - O&A$</option>
<option>Lump - CP$</option>
<option>Lump - VR$</option>
<option>Lump - BB$</option>
</select>
</td>
<td>
<input type="number" name="records[0].Cases">
</td>
<td>
<select name="records[0].EndCurrentDeal">
<option selected="selected" value="true">Yes</option>
<option value="false">No</option>
</select>
</td>
<td>
<input id="dp1363608756707" class="hasDatepicker" type="date" name="records[0].StartDate">
</td>
<td>
<input id="dp1363608756708" class="hasDatepicker" type="date" name="records[0].EndDate">
</td>
<td>
<input type="text" name="records[0].DealRate">
</td>
</tr>
<tr>
<td></td>
<td> Comments: </td>
<td colspan="8">
<input class="comment" type="text" name="records[0].Comments">
</td>
</tr>
</tbody>
<tbody data-entry-index="1">
<tr>
<td>
<input type="checkbox">
</td>
<td>
<input class="lobSelect" type="text" name="records[1].LOB">
</td>
<td>
<input type="text" name="records[1].ProductCode">
</td>
<td>
<input class="product-description" type="text" disabled="disabled" style="background-color: rgb(238, 238, 238);">
</td>
<td>
<select id="records_0__AllowType" name="records[1].AllowType">
<option selected="selected">BillBack$</option>
<option>Billback%</option>
<option>O&A%</option>
<option>Coop%</option>
<option>VR%</option>
<option>Lump - O&A$</option>
<option>Lump - CP$</option>
<option>Lump - VR$</option>
<option>Lump - BB$</option>
</select>
</td>
<td>
<input type="number" name="records[1].Cases">
</td>
<td>
<select name="records[1].EndCurrentDeal">
<option selected="selected" value="true">Yes</option>
<option value="false">No</option>
</select>
</td>
<td>
<input id="dp1363608756709" class="hasDatepicker" type="date" name="records[1].StartDate">
</td>
<td>
<input id="dp1363608756710" class="hasDatepicker" type="date" name="records[1].EndDate">
</td>
<td>
<input type="text" name="records[1].DealRate">
</td>
</tr>
<tr>
<td></td>
<td> Comments: </td>
<td colspan="8">
<input class="comment" type="text" name="records[1].Comments">
</td>
</tr>
</tbody>
</table>
<footer>
<div class="buttonGroup">
<input type="submit" value="Submit Changes">
<input type="button" value="Main Menu">
<input type="button" value="View Customer Deals">
</div>
</footer>
</form>

毫无疑问它就是SelectList。就在昨天我也遇到了同样的问题。

如果您查看 SelectList,它的所有构造函数都需要一个参数。http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist(v=vs.108).aspx

问题是当你的Action叫做public ActionResult Index(TradeSpendingEntryViewModel vm)

控制器尝试绑定发回的数据POST to TradeSpendingEntryViewModel需要根据其设置值PlanningYears它厌倦了通过创建一个新的SelectList

要解决此问题,您需要将 SelectList 设置为私有变量(也称为支持字段),然后默认将其设置为空列表。这为其提供了所需的参数化构造函数:

    //select list
    private SelectList planningYears = new SelectList(new List<YourObject>());

    public SelectList PlanningYears 
    {
        get
        {
            return planningYears;
        }
        set
        {
            locations = planningYears;
        }
    }

或者将 PlanningYears 更改为 List 并将其转换为视图上的选择列表。

@Html.DropDownListFor(m => m.PlanningYears , new SelectList(Model.PlanningYears ), "choose", null)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

默认模型绑定抛出“没有为此对象定义无参数构造函数” 的相关文章

  • 如何使用 Entity Framework Code First 在两个实体之间建立多个一对多关系

    下面是保存关系数据库记录的简单方法 该方法运行得很好 我对一种情况有疑问 在此之前 我需要知道如果数据库复杂性增加 我所采用的方法会遇到什么困难 还有更好 高效但简单的方法吗 一对一 tb student store student det
  • (VS2017)运行所选代码生成器时出错:“序列不包含元素”

    我正在跑过微软的教程之一 https learn microsoft com en us aspnet core tutorials first mvc app 关于 MVC 开发 我在尝试创建各种元素时遇到错误 视图 控制器等 我收到的错
  • 所需的防伪表单字段“__RequestVerificationToken”不存在 用户注册时出错

    我在用Membership create用户函数 然后发生以下错误 所需的防伪表单字段 RequestVerificationToken 为 不存在 我怎样才能解决这个问题 你有 ValidateAntiForgeryToken 执行操作之
  • 是否可以让 ASP.NET MVC 3 项目在 Mono 2.10 下运行?

    Mono 2 10 的发行说明建议支持 ASP NET MVC 3 0 和Razor http weblogs asp net scottgu archive 2010 07 02 introducing razor aspx using
  • 缺少添加控制器/视图的上下文菜单

    我已将 ASP NET MVC 4 集成到现有的 asp net 网站中 两者都工作正常 但我没有看到任何菜单 快捷方式来在 Visual Studio IDE 中创建控制器 视图 这些仅适用于 ASP NET MVC 模板吗 这些仅适用于
  • ASP.NET MVC:这个业务逻辑应该放在哪里?

    我正在开发我的第一个真正的 MVC 应用程序 并尝试遵循一般的 OOP 最佳实践 我正在将控制器中的一些简单业务逻辑重构到我的域模型中 我最近一直在阅读一些内容 很明显我应该将逻辑放在域模型实体类中的某个位置 以避免出现 贫血域模型 反模式
  • 从另一台设备访问 Azure 模拟器

    我有两个不同的项目 Windows Phone 8 应用程序 我正在真实的物理开发设备上运行 Azure 云服务 其中包含一个简单的 WebRole 端点 其中包含 ASP NET MVC WebAPI 我的目标很简单 使用从真实设备运行的
  • SignalR 在子域上协商 404

    我创建了一个小型 MVC SignalR 应用程序 但在子域下的服务器上运行时遇到问题 http chat mydomain com http chat mydomain com 它映射到名为 chat 的文件夹 我还使用 SignalR
  • 过滤文件上传仅用于文本文件

    我使用的是 Firefox 版本 14 0 1 我需要过滤上传文件窗口以仅显示 txt files 我的浏览器不仅仅支持文本文件 text plain 我可以通过指定此格式来限制图像文件 image 但我只需要过滤文本文件在文件选择器窗口中
  • 在 CSHTML 页面中实现 switch 语句

    我正在尝试做一些不同的事情 我有一个包含 ID 的视图 根据 Id 的值 我想更改显示的标题 就像是 switch id case test h1 Test Site h1 case prod h1 Prod Site h1 break 我
  • ASP.NET MVC 多线程

    我想在我的 asp net mvc 应用程序中实现这样的逻辑 user clicks a button gt server executes some time consuming logic in 15 threads i get dat
  • 在 Foreach 或 For 循环中使用 EditorFor (ASP.NET MVC + RAZOR)

    我目前正在实施一个家谱我的 ASP NET MVC 项目中的系统 为了设置家庭成员之间的关系 我需要每行显示两个 ComboBox DropDownList 来定义一个成员与另一个成员之间的关系 首先我将分享我的代码 然后我将解释到目前为止
  • MVC 重定向到没有控制器的视图

    希望应该是一个简单的 我创建了一个通用错误视图 当整个站点的操作方法内发生异常时 我想显示该视图 我创建了一个部分页面 所有导航都位于其中 因此我不需要在此视图上使用控制器 那么如何从控制器内的操作方法重定向到它 像这样的东西 HttpPo
  • 将自定义参数传递给 ValidationAttribute

    我构建了一个自定义 ValidationAttribute 以便可以验证系统中的唯一电子邮件地址 但是 我想以某种方式传递自定义参数 以便为我的验证添加更多逻辑 public class UniqueEmailAttribute Valid
  • 关于实体框架上下文生命周期的问题

    我对 ASP NET MVC 应用程序中实体框架上下文的所需生命周期有一些疑问 让上下文在尽可能短的时间内保持活动状态不是最好的吗 考虑以下控制器操作 public ActionResult Index IEnumerable
  • Google Chrome 客户端的 ASP.NET MVC 路由问题

    我的 Silverlight 4 应用程序托管在 ASP NET MVC 2 Web 应用程序中 当我使用 Internet Explorer 8 浏览时 它工作正常 但是 Google Chrome 版本 5 无法找到 ASP NET 控
  • Active Directory 会员资格提供商 - 如何对此进行扩展?

    我正在努力通过 AD Membership Provider 启动并运行 MVC 应用程序 但在解决这个问题时遇到了一些问题 我有一个基本配置设置并在我登录时工作 电子邮件受保护 cdn cgi l email protection 密码
  • jQuery UI 对话框 + 验证

    我在单击 保存 后使用 Jquery Validate 验证 jQuery UI 对话框时遇到问题 这是我创建 Jquery 对话框的代码 它从目标 href URL 加载对话框 document ready dialogForms fun
  • mvc4 捆绑包,它是如何工作的?

    在 mvc4 中 他们使用捆绑包来调用所有脚本和 css 文件一次 据我所知 调用js和cs文件时 它们的顺序很重要 如果我使用捆绑包 我如何知道捆绑包内的 css 和 js 文件的顺序是否正确 我可以定制订购吗 我现在的日期选择器有问题
  • 使用 LINQ2SQL 在 ASP.NET MVC 中的各种模型存储库之间共享数据上下文

    我的应用程序中有 2 个存储库 每个存储库都有自己的数据上下文对象 最终结果是我尝试将从一个存储库检索到的对象附加到从另一个存储库检索到的对象 这会导致异常 Use 构造函数注入将 DataContext 注入每个存储库 public cl

随机推荐