【发布时间】:2013-11-27 14:03:27
【问题描述】:
我在这里学习 C# 和 mvc4 有点麻烦。
问题出现在我的应用程序的过滤器部分。 我有一个 ViewModel,它可以获取数据库的“Listar_Produtos”列表,以及一些用于搜索选项的字段。
我打算做的是让过滤器接受任何字段,即使它是空值。因为我会根据这些参数制作过滤器。
我有一个视图模型:
using Foolproof;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Ecommerce.Models.Repository
{
public class Produto_Repository
{
public class Index_Listar_Produtos
{
public List<Listar_Produto> Index_List_Produto { get; set; }
[Display(Name = "Data de Cadastro Inicial")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<DateTime> CadastroInicialData { get; set; }
[Display(Name = "Data de Cadastro Final")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[GreaterThanOrEqualTo("CadastroInicialData", ErrorMessage = "\"Data Inicial\", deve ser maior que \"Data Final\"")]
public Nullable<DateTime> CadastroFinalData { get; set; }
}
}
}
我有以下观点:
<td>
@Html.LabelFor(Model => Model.CadastroInicialData)<br />
@Html.TextBoxFor(Model => Model.CadastroInicialData, "{0:dd/MM/yyyy}")
@Html.ValidationMessageFor(Model => Model.CadastroInicialData)
</td>
<td>
@Html.LabelFor(Model => Model.CadastroFinalData)<br />
@Html.TextBoxFor(Model => Model.CadastroFinalData, "{0:dd/MM/yyyy}")
@Html.ValidationMessageFor(Model => Model.CadastroFinalData)
</td>
在我的控制器中,我有:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Filtro(Produto_Repository.Index_Listar_Produtos ViewModel)
{
if (!ModelState.IsValid)
{
Produto_Repository.Index_Listar_Produtos Model_list = Produto_Repository.GetProdutoByAll();
ViewModel.Index_List_Produto = Model_list.Index_List_Produto;
return View("Index", ViewModel);
}
}
其中“Produto_Repository.GetProdutoByAll();”再次返回“产品”列表。
如果我在表单中提供日期,则代码可以正常工作。日期采用“pt-BR”格式:23/03/2013。
但如果我在字段中不提供任何内容(我的视图中的两个日期字段),则“if(!ModelState.IsValid)”返回 true 并输入“if”,因为“CadastroInicialData”和“CadastroFinalData”都带有空值
期望的行为是 ViewModel 可以接受由“Nullable”或“DateTime?”授予的 null 或空值。
我尝试将值插入可空日期字段,执行以下操作:
if (ViewModel.CadastroInicialData == null)
ViewModel.CadastroInicialData = Convert.ToDateTime("01/01/2013");
if (ViewModel.CadastroFinalData == null)
ViewModel.CadastroFinalData = Convert.ToDateTime("01/01/2013");
但现在 ViewModel 返回以下错误: “是无效的日期格式”
一个注意事项是,我正在使用以下“解决方案”来为以下问题转换 pt-BR 日期格式的日期时间: Format datetime in asp.net mvc 4
当文本字段未填充日期时,如何使 ViewModel 接受空值? 我在这里有点困惑。我感谢任何帮助!谢谢!
【问题讨论】:
-
这是您的数据注释,请看我的回复了解原因。
-
嗨@Tommy,数据注释的助手是“GreaterThanOrEqualTo”而不是“GreaterThan”。如果日期时间都为空,则验证成功。
-
...你是 100% 的吗?您的模型状态验证有什么错误?
-
我相信问题来自“ApplyFormatInEditMode = true”。我发布一个答案只是让你解决这个问题。如果您真的想修复它,请查看此链接,它可能会对您有所帮助。 stackoverflow.com/questions/13253964/…
标签: c# asp.net-mvc asp.net-mvc-4 datetime mvvm