在您的post方法中,請在那裏檢查並使用WeightTo和WeightFrom的可爲空的整數。我創建了一個DotNetFiddle這裏爲你https://dotnetfiddle.net/ci0V2I
控制器
[HttpGet]
public ActionResult Index()
{
return View(new SampleModel());
}
[HttpPost]
public ActionResult Index(SampleModel model)
{
if(model.WeightFrom.HasValue && model.WeightTo.HasValue)
{
if(model.WeightFrom.Value < model.WeightTo.Value)
{
ModelState.AddModelError("", "Weight from most be smaller than Weight to. Please fix this error.");
}
}
if(!ModelState.IsValid)
{
return View(model);
}
return View(new SampleModel());
}
型號
using System;
using System.ComponentModel.DataAnnotations;
namespace HelloWorldMvcApp
{
public class SampleModel
{
[Display(Name = "Weight Form")]
public int? WeightFrom { get; set; }
[Display(Name = "Weight To")]
public int? WeightTo { get; set; }
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
}
}
查看
@model HelloWorldMvcApp.SampleModel
@{
Layout = null;
}
@using (Html.BeginForm())
{
@Html.ValidationSummary()
<div class="form-group">
@Html.LabelFor(m => m.WeightFrom)
@Html.TextBoxFor(m => m.WeightFrom, new {@class="form-control"})
@Html.ValidationMessageFor(m => m.WeightFrom)
</div>
<div class="form-group">
@Html.LabelFor(m => m.WeightTo)
@Html.TextBoxFor(m => m.WeightTo, new {@class="form-control"})
@Html.ValidationMessageFor(m => m.WeightTo)
</div>
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new {@class="form-control"})
@Html.ValidationMessageFor(m => m.Name)
</div>
<button type="submit" class="btn btn-success submit">Save</button>
}
並不清楚你問 - 屬性的使用確保了'WeightTo '大於'WeightFrom'的值,這似乎是你想要的,但是製作這個prope rties typeof'string'沒有任何意義 - 它們需要是數字類型,例如'int' –
使它作爲字符串仍然做同樣的事情,但如果我離開這個重量範圍空白,那麼它仍然使它紅色填充。但是這些範圍字段的系統標準是可選的。 – barsan
然後,你將需要懷疑你自己的驗證屬性(說)'[GreaterThanIf]' –