C#MVC 4视图模型不接受空的DateTime [英] C# MVC 4 ViewModel not accepting null DateTime

查看:287
本文介绍了C#MVC 4视图模型不接受空的DateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是有点麻烦,在这里学习C#和mvc4。

I'm in a bit of trouble here learning C# and mvc4.

问题在我的应用程序的过滤器部分发生。
我有抓住数据库Listar_Produtos,和搜索选项的一些字段列表的视图模型。

The Problem occurs in the Filter part of my application. I have an ViewModel that grabs the list of "Listar_Produtos" of the database, and some fields for searching options.

我打算做的是使什么过滤接受任何领域,即使是空值。因为我要让基于这些paramters过滤器

What I intend to do is make the filter accept any field, even if it's null values. Because i'll make the filter based on these paramters.

我有一个视图模型:

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再次名单。

Where "Produto_Repository.GetProdutoByAll();" returns the list of "Produtos" again.

中的代码工作正常,很好,如果我在表格中填入日期。日期是PT-BR的格式:23/03/2013

The code works fine and well if I provide dates in the form. The dates are in "pt-BR" format: 23/03/2013.

但是,如果我什么都不提供在字段(包括Datefields在我看来),比如果(!ModelState.IsValid)返回true,进入如果,因为这两个CadastroInicialData和CadastroFinalData自带空值

But if I provide nothing in the Fields (both Datefields in my View), than the "if(!ModelState.IsValid)" returns true and enters the "if", because both "CadastroInicialData" and "CadastroFinalData" comes with null values

期望的行为是该视图模型可以接受由可空或日期时间?授予空或空值。

The desired behavior is that the ViewModel could accept null or empty values that are granted by "Nullable" or "DateTime?".

我tryed插入值可空日期字段执行以下操作

I Tryed to insert values to the nullable date fields doing the following:

if (ViewModel.CadastroInicialData == null)
    ViewModel.CadastroInicialData = Convert.ToDateTime("01/01/2013");
if (ViewModel.CadastroFinalData == null)
    ViewModel.CadastroFinalData = Convert.ToDateTime("01/01/2013");



但现在的视图模型返回以下错误:
是无效的日期格式为

But now the ViewModel returns the following error: "is an invalid date format"

注意的一点是我使用的以下问题转换为日期时间PT-BR DATEFORMAT以下解决方案:

One note is that i'm using the following 'solution' for converting datetimes for pt-BR dateformat on the following question: Format datetime in asp.net mvc 4

如何让视图模型接受空值时,文本字段没有填写的日期?
我有点困惑在这里。我apreciate任何帮助!谢谢!

How I make the ViewModel accept null values when the text fields are not filled with dates? I'm kinda confused here. I apreciate any help ! Thanks !

推荐答案

您可以在另一个属性添加到您的模型类,然后用它们来确定值为null或不是。也实现了他们在您的视图。请参见下面的代码:

You can add another properties to your Model class, then use them to determine if the value is null or not. Also implement them in your view. See below code:

型号

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; }


    public string GetStringTypeCadastroInicialData
    {
        get { return CadastroInicialData != null ? CadastroInicialData.Value.ToShortDateString() : DateTime.MinValue.ToShortDateString()(Or empty string ); }
    }

    public string GetStringTypeCadastroFinalData
    {
        get { return CadastroInicialData != null ? CadastroFinalData.Value.ToShortDateString() : DateTime.Now.ToShortDateString(); }
    }

}

查看

<td>
    @Html.LabelFor(Model => Model.GetStringTypeCadastroInicialData)<br />
    @Html.TextBoxFor(Model => Model.GetStringTypeCadastroInicialData)
    @Html.ValidationMessageFor(Model => Model.GetStringTypeCadastroInicialData)
</td>
<td>
    @Html.LabelFor(Model => Model.GetStringTypeCadastroFinalData)<br />
    @Html.TextBoxFor(Model => Model.GetStringTypeCadastroFinalData)
    @Html.ValidationMessageFor(Model => Model.GetStringTypeCadastroFinalData)
</td>

这篇关于C#MVC 4视图模型不接受空的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆