我在学习 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();”再次返回“Produtos”列表。
如果我在表单中提供日期,该代码可以正常工作。日期采用“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 日期格式,以解决以下问题:在 asp.net mvc 4 中格式化日期时间 https://stackoverflow.com/questions/11272851/format-datetime-in-asp-net-mvc-4
当文本字段未填充日期时,如何使 ViewModel 接受空值?
我在这里有点困惑。我很感激任何帮助!谢谢 !