Change ModelState In viewmodel(Add Custom Validation)

I am new to Web programming and i had to use Jquery datatime plugin. I was having a lot of problem in datatime conversions so i made a simple to me but weird and long logic to deal with it. Instead of creating One DateTime property. I made two, One is string and other is nullable Datetime in ViewModel

Note:All this code is written in 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";
              }
            }
        }
    }

Kindly tell me how to deal with it nicely.

Secondly

For instance this logic is good and then i want to add ModelState Error. Forexample

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

Is there anything like that. Please help and thanks a lot for reading all my question :)

Forexample i parse it like that

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

and value is 1/1/201 it will throw an exception. I don't want it to throw an exception but add an Validation Error, so later in controller when i check ModelState.IsValid it returns false and i can show it in 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" })

I am Setting its value from view.

With All other Properties in my model. I have this

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

Answers 1

  • Use try-catch block and add ModelState.AddModelError into your code:

    View

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

    Controller

    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 will invalidate the ModelState and as a result IsValid property becomes false when returning your view.

    Probably this is far from your current needs, thus any suggestions welcome.


Related Articles