在viewmodel中更改ModelState(添加自定义验证)

时间:2016-07-15 05:48:05

标签: c# jquery validation viewmodel modelstate

我是Web编程的新手,我不得不使用Jquery datatime插件。我在数据转换过程中遇到了很多问题,所以我对我做了一个简单但很奇怪的长逻辑来处理它。 而不是创建一个DateTime属性。我做了两个,一个是字符串,另一个是ViewModel中可以为空的Datetime

注意:所有这些代码都是用ViewModel

编写的
  public DateTime? InitialStartDate
    {
        get
        {
            return istartDate;
        }
        set
        {
            istartDate = value;
        }
    }

    public string IStartDateString
    {
        get
        {
            if (istartDate == null)
            {
                return "";
            }
            else
            {
                return istartDate.Value.ToString("MM/dd/yyyy");
            }
        }
        set
        {
            if (string.IsNullOrEmpty(value))
            {
                istartDate = null;
            }
            else
            {
                DateTime TempDate=DateTime.Min;
                if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
                {
                  InitialStartDate=TempDate;
                }
                 else{
                  InitialStartDate=null;
                  ErrorMessage="Can not convert date";
              }
            }
        }
    }

请告诉我如何妥善处理它。

其次

例如这个逻辑很好然后我想添加ModelState错误。 Forexample

            if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
                {
                  InitialStartDate=TempDate;
                }
                 else{
                  InitialStartDate=null;
                  ModelState.AddError('Date is not right ');
              }

有类似的东西吗?请阅读我的所有问题,请多多帮助和感谢:)

例如我解析它

InitialStartDate= DateTime.ParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture);

且值为1/1/201 它会引发异常。我不希望它抛出异常但添加验证错误,所以稍后在控制器中检查ModelState.IsValid 它返回false,我可以在View中显示它。

      @Html.LabelFor(model => model.InitialStartDate, htmlAttributes: new { @class = "control-label col-offset-2" })
      @Html.TextBoxFor(model => model.IStartDateString, new { @id = "initialstartdate", value = Model.IStartDateString, @class = "form-control", tabindex = "34" })
      @Html.ValidationMessageFor(model => model.InitialStartDate, "", new { @class = "text-danger" })

我正在从视图中设置其值。

在我的模型中使用所有其他属性。我有这个

       [DataType(DataType.Date)]
       public DateTime? StartTime { get; set; }

2 个答案:

答案 0 :(得分:1)

试试这个

$(function() {
    $("#datepicker").datepicker({
        changeMonth: true,
        changeYear: true,
        yearRange: '2011:2037',
        dateFormat: 'dd/mm/yy',
        minDate: 0,
        defaultDate: null
    }).on('change', function() {
        $(this).valid();  // triggers the validation test
        // '$(this)' refers to '$("#datepicker")'
    });
});

我希望它会对你有所帮助。

答案 1 :(得分:0)

使用try-catch块并在代码中添加ModelState.AddModelError

查看

<script type="text/javascript">
    $(document).ready(function() {
        $("#initialstartdate").datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'MM/dd/yyyy',
            minDate: 0,
            defaultDate: null
            // see jQuery datepicker docs for more attributes
        }).change(function() {
            $(this).valid(); // validation test
        });
    });
</script>

<!-- EditorFor used to include datetime as is -->
@Html.EditorFor(model => model.IStartDateString, new { @id = "initialstartdate", value = Model.IStartDateString, @class = "form-control", tabindex = "34" });

控制器

try {
        if(DateTime.TryParseExact(value, "MM/dd/yyyy", CultureInfo.InvariantCulture, out TempDate)
        {
             InitialStartDate=TempDate;
        }
        else 
        {
             InitialStartDate = null;
             ModelState.AddModelError("Date is not right");
        }
}
catch (ArgumentException e)
{
    ModelState.AddModelError("Date is not right");
}

ModelState.AddModelError会使ModelState无效,因此返回视图时IsValid属性会变为false

可能这远远不是您目前的需求,因此欢迎任何建议。

相关问题