【问题标题】:TextboxFor in EditorTemplate does not save valueEditorTemplate 中的 TextboxFor 不保存值
【发布时间】:2016-07-20 08:59:39
【问题描述】:

我在 MVC 中使用 EditorTemplate 时遇到问题。

我的 EditorTemplate 如下所示:

    <script type="text/javascript">
    $(function () {
        $('.datepicker').datepicker({
            dateFormat: 'dd-mm-yy'
        });
    });
</script>

<tr>
    <td>@Html.DisplayFor(model => model.Title)</td>
    <td>@Html.DisplayFor(model => model.Authors)</td>
    <td><a href="/administration/products/bookz/bookform.aspx?book=@Model.BookId" target="_blank">@Html.DisplayFor(model => model.ISBN13)</a></td>
    <td>@extPrice.ToString("N2") </td >
    <td>@Html.TextBoxFor(model => model.Price, new { data_val_number = "The field Price must be a number." })</td>
    <td>@Html.TextBoxFor(model => model.MemberPriceStartDate, "{0:dd-MM-yyyy}", new { @class = "form-control datepicker" })</td>
    <td>@Html.TextBoxFor(model => model.MemberPriceEndDate, "{0:dd-MM-yyyy}", new { @class = "form-control datepicker" })</td>
    @Html.HiddenFor(model => model.BookId)
</tr>

@model 的类型为 Books(由于数据库混乱 -_-,Books 是单数)。

EditorTemplate 从视图中调用,如下所示:

@Html.EditorFor(model => model)

其中@model 的类型为IEnumerable&lt;Books&gt;

当发布到我的控制器时,Books.Price 被正确传递,但 Books.MemberPriceStartDateBooks.MemberPriceEndDate 始终为空。 隐藏字段Books.BookId也传递正确。

关于为什么会发生这种情况的任何想法?

编辑:

以下是Books 对象的相关属性:

public Nullable<System.DateTime> MemberPriceStartDate { get; set; }
public Nullable<System.DateTime> MemberPriceEndDate { get; set; }
public Nullable<decimal> Price { get; set; }
public int BookId { get; set; }

【问题讨论】:

  • 第一件事是你说的是你在谈论这个“@Html.EditorFor(model => model) 的列表视图/索引页面,其中@model 的类型是 IEnumerable。”其次,对于您的编辑器视图,尝试从控制器视图中调试模型,就像模型一样。有值如果有值然后删除日期格式“{0:dd-MM-yyyy}”并查看。
  • @DhakaPariBahan I've now checked using Fiddler - The values are posted correctly - this is the string from Fiddler: __RequestVerificationToken=5NlvZ0suitm6E7SS859qIkpuDdGgMxydw37NgY9NMbk04aWwqjTocSXMkstQAHOJ2337Ja8dEE-Hjq01kEExAd8cq7TRaQ51VPSj2WHWY1KPmp7m6jLXBM1u5v7WiLkK0&%5B0%5D.Price=29%2C00&%5B0%5D .MemberPriceStartDate=19-07-2016&%5B0%5D.MemberPriceEndDate=30-07-2016&%5B0%5D.BookId=352757&%5B1%5D.Price=49%2C00&%5B1%5D.MemberPriceStartDate=&%5B1%5D .MemberPriceEndDate=&%5B1%5D.BookId=353782&%5B2%5D.Price=99%2C00&%5B2%5D.MemberPriceStartDate=&%5B2%5D.MemberPriceEndDate=&%5B2%5D.BookId=353583
  • 你有什么样的IEnumerable&lt;Books&gt;Html.TextBoxFor 默认返回字符串,这需要显式转换/解析以 POST 为 DateTime 值。 Html.EditorFor 可能适合处理日期时间值。
  • @TetsuyaYamamoto 将其更改为 EditorFor 没有任何不同。将使用相关属性的类型更新原始帖子。
  • 用 Visual Studio 调试。

标签: c# asp.net-mvc mvc-editor-templates asp.net-mvc-5.2


【解决方案1】:

在特定字段的模型日期格式中和 您输入的日期格式-"dateFormat: 'dd-mm-yy'" 可能不匹配。

【讨论】:

  • 它们不一样的原因是因为 datePicker javascripy,如果我将 dateFormat: 'dd-mm-yy 更改为 dateFormat: 'dd-mm-yyyy - 它会显示年份2次:-)
猜你喜欢
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多