1

我在MVC項目中使用萬無一失。 我遇到了麻煩,它似乎在進行文本比較以確定結束日期時間是否大於開始日期時間。使用萬無一失,以確保結束日期時間大於開始日期時間

這裏是模型:

public class TestModel 
{ 
    [Required] 
    [DataType(DataType.DateTime)] 
    public DateTime start { get; set; } 

    [Required] 
    [DataType(DataType.DateTime)] 
    [GreaterThan("start")] 
    public DateTime end { get; set; } 
} 

認爲

@model WebApplication1.Models.TestModel 

@{ 
    ViewBag.Title = "Home Page"; 
} 


@using (Html.BeginForm("Index2", "Home", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) 
{ 
    @Html.AntiForgeryToken() 

    @Html.ValidationSummary("", new { @class = "text-danger" }) 
    <div class="form-group"> 
     @Html.LabelFor(m => m.start, new { @class = "col-md-2 control-label" }) 
     <div class="col-md-10"> 
      @Html.TextBoxFor(m => m.start, "{0:dd/MM/yyyy HH:mm}", new { @class = "form-control datetimepicker" }) 
     </div> 
    </div> 
    <div class="form-group"> 
     @Html.LabelFor(m => m.end, new { @class = "col-md-2 control-label" }) 
     <div class="col-md-10"> 
      @Html.TextBoxFor(m => m.end, "{0:dd/MM/yyyy HH:mm}", new { @class = "form-control datetimepicker" }) 
     </div> 
    </div> 
    <div class="form-group"> 
     <div class="col-md-offset-2 col-md-10"> 
      <input type="submit" value="Set password" class="btn btn-default" /> 
     </div> 
    </div> 
} 

@section Scripts { 
    @Scripts.Render("~/bundles/jqueryval") 
} 

控制器

public ActionResult Index() 
    { 
     TestModel model = new TestModel(); 
     // model.start = new DateTime(2016, 5, 31); 
     //model.end = new DateTime(2016, 8, 31); 
     model.start = DateTime.Now; 
     model.end = DateTime.Now.AddMinutes(30); 
     return View(model); 
    } 

您可以下載我的項目嘗試: https://www.dropbox.com/s/pf0lkg297hq0974/WebApplication1.zip?dl=0

有兩個問題: 1)當你開始日期11/07/2016 23:51和結束日期02/08/2016 00:21你會得到一個驗證錯誤,因爲它認爲結束日期小於開始日期。這似乎與我的文字比較。 2)另外,如果您取消註釋掉兩個model.start和model.end日期初始化語句,則在提交時會得到無效日期。

注意我在使用引導程序datetimepicker,但在文檔準備就緒時將它初始化的位註釋掉了。我認爲這與這個問題有關,但似乎沒有。最終我想讓datetimepicker工作。

另外請注意,我在澳大利亞這樣的日期格式爲DD/MM/YYYY

+0

我猜萬無一失是越野車在這裏。任何其他方式做註釋驗證? – rukiman

+0

問題是'jquery.validate.js'(用於萬無一失)根據'MM/dd/yyyy'格式驗證日期(所以'end = 02/08/2016'是2月8日和'start = 11/07/2016'是12月7日,意思是'end'小於'start')。參考[這個答案](http://stackoverflow.com/questions/39677035/date-of-birth-validation-keeps-showing/39682410#39682410)的一些選項。 –

+0

另外[這個答案](http://stackoverflow.com/questions/27285458/jquery-ui-date-picker-and-mvc-view-model-type-datetime/27286969#27286969)如果你使用jquery-ui datepicker(我假設引導程序datetimepicker也將有一個類似的方法來解析這個值到一個特定的日期格式) –

回答

1

在HTML烏爾張貼到索引2回改變對指數 字符串轉換爲DateTime在GreaterThanAttribute在你的應用程序,然後比較

試試這個我已經測試了這個實現

的控制器

public class TestController : Controller 
{ 
    // GET: Test 

    [HttpGet] 
    public ActionResult Index() 
    { 

     var model = new TestModel(); 
     // model.start = new DateTime(2016, 5, 31); 
     //model.end = new DateTime(2016, 8, 31); 
     model.start = DateTime.Now; 
     model.end = DateTime.Now.AddMinutes(30); 
     return View(model); 


    } 
    [HttpPost] 
    public ActionResult Index(TestModel model) 
    { 
     if (ModelState.IsValid) 
     { 

      // model.start = new DateTime(2016, 5, 31); 
      //model.end = new DateTime(2016, 8, 31); 
      model.start = DateTime.Now; 
      model.end = DateTime.Now.AddMinutes(30); 
      return View("Index", model); 
     } 
     return View("Index", model); 

    } 
} 

呦烏爾TestModel

public class TestModel 
{ 
    [Required] 
    [DataType(DataType.DateTime)] 
    public DateTime start { get; set; } 

    [Required] 
    [DataType(DataType.DateTime)] 
    [GreaterThan("start", "Your Error Message")] 
    public DateTime end { get; set; } 
} 

您GreaterThenAttribute.cs

public class GreaterThanAttribute : ValidationAttribute, IClientValidatable 
{ 

    public string otherPropertyName; 
    public GreaterThanAttribute() 
    { 
    } 
    public GreaterThanAttribute(string otherPropertyName, string errorMessage) : base(errorMessage) 
    { 
     this.otherPropertyName = otherPropertyName; 
    } 

    protected override ValidationResult IsValid 
     (object value, ValidationContext validationContext) 
    { 
     ValidationResult validationResult = ValidationResult.Success; 
     try 
     { 
      // Using reflection we can get a reference to the other date property, in this example the project start date 
      var containerType = validationContext.ObjectInstance.GetType(); 
      var field = containerType.GetProperty(this.otherPropertyName); 
      var extensionValue = field.GetValue(validationContext.ObjectInstance, null); 
      var datatype = extensionValue.GetType(); 

      //var otherPropertyInfo = validationContext.ObjectInstance.GetType().GetProperty(this.otherPropertyName); 
      if (field == null) 
       return new ValidationResult(String.Format("Unknown property: {0}.", otherPropertyName)); 
      // Let's check that otherProperty is of type DateTime as we expect it to be 
      if ((field.PropertyType == typeof(DateTime) || 
       (field.PropertyType.IsGenericType && field.PropertyType == typeof(Nullable<DateTime>)))) 
      { 
       DateTime toValidate = (DateTime)value; 
       DateTime referenceProperty = (DateTime)field.GetValue(validationContext.ObjectInstance, null); 
       // if the end date is lower than the start date, than the validationResult will be set to false and return 
       // a properly formatted error message 
       if (toValidate.CompareTo(referenceProperty) < 1) 
       { 
        validationResult = new ValidationResult(ErrorMessageString); 
       } 
      } 
      else 
      { 
       validationResult = new ValidationResult("An error occurred while validating the property. OtherProperty is not of type DateTime"); 
      } 
     } 
     catch (Exception ex) 
     { 
      // Do stuff, i.e. log the exception 
      // Let it go through the upper levels, something bad happened 
      throw ex; 
     } 

     return validationResult; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules 
     (ModelMetadata metadata, ControllerContext context) 
    { 
     var rule = new ModelClientValidationRule 
     { 
      ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), 
      ValidationType = "isgreater", 
     }; 
     rule.ValidationParameters.Add("otherproperty", otherPropertyName); 
     yield return rule; 
    } 
} 
+0

我不太明白。你能粘貼代碼嗎? – rukiman

+0

@rukiman我已更新我的答案並粘貼了代碼 – gurdeep

相關問題