MVC 5没有正确验证StringLength属性

时间:2014-11-19 12:15:34

标签: c# asp.net-mvc entity-framework model asp.net-mvc-5

我尝试验证PersonPaymentDetails模型中的sortCode字段,但我的视图未能验证StringLength(6)。如果我提交的表格长度为1,则表示错误验证成功。

我在这里做了一些根本错误的事情吗?

/* [CONTROLLER] */
public class PersonController : Controller
{
  [HttpGet]
  [Route("person/paymentDetails/create/{personId?}")]
  public ActionResult PaymentDetailsCreate(int? personId)
  {
      if (personId == null)
      {
          return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
      }
      Person person = db.People.Find(personId);

      if (person == null)
      {
          return HttpNotFound();
      }

      PersonPaymentDetailsViewModel personPaymentDetailsVM = new PersonPaymentDetailsViewModel();
      personPaymentDetailsVM.SetPerson(person);

      return View(personPaymentDetailsVM);
  }

  [HttpPost]
  [Route("person/paymentDetails/create")]
  public ActionResult PaymentDetailsCreate(PersonPaymentDetailsViewModel personPaymentDetailsVM)
  {
      if (ModelState.IsValid)
      {
          /* should not be entering here with sortCode = 123, as not 6 characters in length */
          return Content("No errors: |" + personPaymentDetailsVM.SinglePaymentDetails.sortCode + "|");
      }
  }
}

/* [VIEW] */
@model X.ViewModels.PersonPaymentDetailsViewModel

@Html.ValidationSummary()
@using (Html.BeginForm("PaymentDetailsCreate", "Person", FormMethod.Post, new { @class = " form-horizontal" }))
{
    @Html.HiddenFor(m => m.Person.id, "default")

    <div class="form-group">
        <label for="bankSortCode" class="col-md-3 control-label">Sort Code</label>
        <div class="col-md-9">
            @Html.EditorFor(m => m.SinglePaymentDetails.sortCode, new { htmlAttributes = new { @class = "form-control" } })
        </div>
    </div>

    <div class="form-group">
        <label for="save" class="col-md-3 control-label">&nbsp;</label>
        <div class="col-md-9">
            <button type="submit" class="btn btn-primary">Save</button>
        </div>
    </div>
}

/* [MODEL] */
public partial class PersonPaymentDetails
{
    public int id { get; set; }

    [Required, StringLength(6)]
    public string sortCode { get; set; }
}

/* [ViewModel] */
public class PersonPaymentDetailsViewModel
{
    public Person Person { get; set; }
    public PersonPaymentDetails SinglePaymentDetails { get; set; }

    public void SetPerson(Person person)
    {
        this.Person = person;
        this.SinglePaymentDetails = new PersonPaymentDetails();
    }
}

1 个答案:

答案 0 :(得分:7)

你想要

[Required, StringLength(6, MinimumLength = 6)]

StringLength的构造函数仅占用最大长度,因此当前使用它时它会检查字符串是否不超过6个字符,因此长度为1的字符串成功通过验证。