[英]Dropdown Custom Validation message being overriden in MVC
我是MVC菜鳥,並且嘗試通過添加ModelState.modelerror驗證下拉列表並顯示自定義錯誤消息。 在我內部,字段“ Board”是屏幕上顯示的下拉列表,稱為“ ProviderId”。 在UI上,當我沒有從下拉列表中選擇一個值時,我希望看到消息“ Board不能為空”,但我只看到“ ProviderId字段為必填”。 此方法似乎適用於其他編輯字段。
這是我的控制器代碼
[HttpPost]
public ActionResult Create(CourseList courselist)
{
//This works! It shows Class Name cannot be Empty next to class field on submit
if (courselist.CourseName == null)
{
ModelState.AddModelError("CourseName", " Class Name cannot be Empty");
ViewBag.ProviderID = new SelectList(db.ProviderLists, "ProviderID", "ProviderName", courselist.ProviderID);
return View(courselist);
}
//This does not work! It shows the internal binding message instead of this custom message
if (courselist.ProviderID == null)
{
ModelState.AddModelError("ProviderID", " Board cannot be Empty");
ViewBag.ProviderID = new SelectList(db.ProviderLists, "ProviderID", "ProviderName", courselist.ProviderID);
return View(courselist);
}
if (ModelState.IsValid)
{
db.CourseLists.Add(courselist);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ProviderID = new SelectList(db.ProviderLists, "ProviderID", "ProviderName", courselist.ProviderID);
return View(courselist);
}
這是我的相關查看代碼
<div class="editor-field">
@Html.DropDownList("ProviderID", String.Empty)
@Html.ValidationMessageFor(model => model.ProviderID)
</div>
對於其他兩個編輯字段,它工作正常,即在我提交時在該字段旁邊打印自定義消息,但始終將內部綁定消息“ providerId字段為必需”作為下拉列表。 我必須怎么做才能將消息更改為自定義添加的消息。 這發生在代碼中所有我的下拉列表中! ProviderId是數據庫中的必填字段,可能會立即看到該消息,但是如何覆蓋它以顯示自定義消息? 也許這是一個簡單的修復程序,但是我對MVC總體上不滿意(2小時),並且想解決此問題
“木板不能為空”
編輯 :該字段是ProviderID
我想,你正在使用的數據庫第一(或模型一)的方式,所以你有一個edmx
文件和相應的.Designer.cs
文件。 在最后一個文件中,您可能會有類似以下內容:
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ProviderID
在這里,類型int
不可為空,並且屬性具有元數據屬性IsNullable=false
。 這就是ASP.NET MVC提供默認錯誤消息的原因。
一個簡單的解決方法是將db上的字段設置為非必需字段,然后更新模型。 之后,您應該在.Designer.cs
看到以下內容:
[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> ProviderID
現在,您可以看到自定義消息“ Board不能為空”。
更好的方法(而不是更改數據庫和模型)是從if (courselist.ProviderID == null)...
刪除並使用元數據。 這是一個片段:
[MetadataType(typeof(YourEntityMetaData))]
public partial class YourEntity
{
}
public class YourEntityMetaData
{
[Required(ErrorMessage = "Board cannot be empty")]
public int ProviderID { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.