Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net mvc 3 Html.EditorFor nullable DateTime从视图以null形式发回_Asp.net Mvc 3_C# 4.0_Post_Null_Editorfor - Fatal编程技术网

Asp.net mvc 3 Html.EditorFor nullable DateTime从视图以null形式发回

Asp.net mvc 3 Html.EditorFor nullable DateTime从视图以null形式发回,asp.net-mvc-3,c#-4.0,post,null,editorfor,Asp.net Mvc 3,C# 4.0,Post,Null,Editorfor,让我们做出以下假设;ASP.NET MVC 3 Razor C#,一个绑定到视图模型(非实体等)的强类型视图,使用Html.EditorFor方法编辑视图模型中的可空DateTime属性。我添加的两个数据注释属性似乎导致模型绑定失败 示例视图代码 @model MyApp.ViewModels.NullableDateTimeViewModel @using (Html.BeginForm()) { @Html.EditorFor(m => m.DateOfBirth) } V

让我们做出以下假设;ASP.NET MVC 3 Razor C#,一个绑定到视图模型(非实体等)的强类型视图,使用Html.EditorFor方法编辑视图模型中的可空DateTime属性。我添加的两个数据注释属性似乎导致模型绑定失败

示例视图代码

@model MyApp.ViewModels.NullableDateTimeViewModel

@using (Html.BeginForm())
{
    @Html.EditorFor(m => m.DateOfBirth)
}
ViewModel代码示例

[DataType(DataType.Date,
    ErrorMessage = "Please enter a valid date in the format dd MMM yyyy")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
public class NullableDateTimeViewModel
{
    public DateTime? DateOfBirth { get; set; }
}
示例控制器代码

[HttpPost]
public ViewResult DoB(NullableDateTimeViewModel nullableDateTimeVM)
{
    ContextDB db = new ContextDB();

    Customer cust = new Customer();

    // DateOfBirth is null so the update fails
    cust.DateOfBirth = nullableDateTimeVM.DateOfBirth.Value;

    db.Customers.Add(cust);
    db.SaveChanges();
}
添加数据批注属性时,提交视图中的表单时,视图中输入的数据不会发回控制器。这意味着在将EditorFor与这些属性一起使用时,模型绑定失败。模型绑定可以与TextBoxFor配合使用,在TextBoxFor输入框中输入的值将通过视图模型传递回视图。EditorFor和数据批注验证属性存在什么问题


我们能否找到一个解决方案,不需要通过创建多个附加类、助手、模板和编写大量附加代码来重新设计轮子?我正在寻找一个一行或两行的解决方案。

我认为您不需要
。值
DateOfBirth应该是DateTime?类型?。我会设置一个断点并观察nullableDateTimeVM,然后您可以检查DateOfBirth属性的值。我确实认为需要该值,但我正在检查一些数据注释属性,看看它们是否是问题所在。是的,问题是由两个数据注释验证属性引起的,这两个属性都会导致模型绑定失败。当它们被删除时,editorfor可以正常工作。是否有DateTime类型的EditorTemplate?如果是,我们能看到代码吗?使用TextBoxFor时,您将呈现一个输入html元素。但是当你说EditorFor时,它会在你的项目中查找EditorTemplate,如果找不到它,它会使用默认值。我没有使用EditorTemplate。