你好,我想請問ASP.NET MVC的模型驗證寫法這樣是否有誤
測試過後發現ModelState.IsValid不管怎樣都會是True
DisplayName則是能正常顯示
程式碼如下
謝謝,新年快樂!
namespace _1119Work.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
public partial class Member
{
[DisplayName("密碼")]
[StringLength(maximumLength:8,ErrorMessage = "密碼長度勿超過8個字元")]
public string Mem_password { get; set; }
}
}
namespace _1119Work.Controllers
{
public class HomeController : Controller
{
public ActionResult CreateMember()
{
return View();
}
[HttpPost]
public ActionResult CreateMember(string Mem_password)
{
if(ModelState.IsValid)
{
return Content("驗證通過");
}
return Content("驗證不通過");
}
}
}
<div class="form-group">
@Html.LabelFor(Model => Model.Mem_password, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Mem_password, new { htmlAttributes = new { @class = "form-control",type = "password"} })
@Html.ValidationMessageFor(model => model.Mem_password, "", new { @class = "text-danger" })
</div>
</div>