【发布时间】:2021-09-10 04:27:33
【问题描述】:
我有一个带有一些验证规则的模型,例如最小字符串长度为 12。
public class Client{
[Required("ID Cannot be empty")]
[StringLength(12, ErrorMessage="ID must have 12 characters", MinimumLength = 12)]
public string Id { get; set; }
[Required("Name cannot be empty")]
[StringLength(60, ErrorMessage="Must be between 10 and 60 characters", MinimumLength = 10)]
public string FullName { get; set; }
[Required("Phone cannot be empty")]
[StringLength(9, ErrorMessage="Phone number must have 9 characters", MinimumLength = 9)]
public string PhoneNumber { get; set; }
[Required("Client needs a status")]
public bool PremiumStatus { get; set; }
}
这些规则在我拥有的Registration 视图中起作用,这意味着我可以看到验证消息,并且如果模型无效,则不会注册模型。
但是,在我的搜索/编辑视图中,我应该能够查找 Id 并修改返回的模型,但没有任何更改正在注册,并且在调试应用程序时,我看到模型的 ModelState 始终无效,但是同时,我没有看到任何验证消息
@model MyApp.Models.Client
@{
ViewBag.Title = "MyApp"
}
@using(Html.BeginForm("Search", "Search", FormMethod.Post)){
Search for ID: @Html.TextBox("SearchId")
<input type="submit" value="Search"/>
}
@using(Html.BeginForm("EditClient", "Search", FormMethod.Post)){
@Html.LabelFor(m => m.Id)
@Html.DisplayFor(m => m.Id)
@Html.LabelFor(m => m.FullName)
@Html.EditorFor(m => m.FullName)
@Html.ValidationMessageFor(m => m.FullName)
@Html.LabelFor(m => m.PhoneNumber)
@Html.EditorFor(m => m.PhoneNumber)
@Html.ValidationMessageFor(m => m.PhoneNumber)
@Html.LabelFor(m => m.PremiumStatus)
@Html.EditorFor(m => m.PremiumStatus)
@Html.ValidationMessageFor(m => m.PremiumStatus)
<input type="submit" value="Save Changes"/>
}
请注意,我只想编辑姓名、电话和状态。我不想编辑 ID,因此它只是一个显示字段
现在在我的控制器上
public class SearchController : Controller {
public ActionResult Search() {
return View();
}
[HttpPost]
public ActionResult Search(string SearchId) {
//Searching my Session variable to retrieve Client item related to the code searched.
//I have validations in place in case the ID doesn't exist, but I'm not showing them to keep the code simple.
Client clientFound = (Client) Session[SearchId];
//Returns the view with the found model, populating all of the fields in the view.
return View("Search", clientFound)
}
[HttpPost]
//I just added these 2 annotations, but it wasn't working without them either
[ValidateAntiForgeryToken]
[ValidateInput(true)]
public ActionResult EditClient(Client model) {
if(ModelState.IsValid){
Session[model.Id] = model;
Debug.WriteLine("Client updated");
}
return RedirectToAction("Search");
}
}
通过设置断点,我可以看到一旦进入EditClient,模型确实分配了正确的、新更新的属性。只是它总是被认为是无效的。如前所述,即使我从可编辑字段中删除所有内容,我也不会收到显示它们无效的错误消息。
【问题讨论】:
-
您是否在编辑时发送防伪令牌?
标签: c# asp.net asp.net-mvc razor