简体   繁体   中英

Dropdown Custom Validation message being overriden in MVC

I am a MVC noob and I am trying to validate dropdownlists and show custom Error message by adding ModelState.modelerror. Internally my field "Board" which is a dropdown list shown on screen is called "ProviderId". On the UI, I want to see the message "Board cannot be empty" when i dont select a value from the dropdown , but I just see "ProviderId field is required" . This method seems to work for other edit fields.

This is my Controller Code

  [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);
        }

This is my relevant View code

 <div class="editor-field">
            @Html.DropDownList("ProviderID", String.Empty)
            @Html.ValidationMessageFor(model => model.ProviderID)
        </div>

It works fine for the other two edit fields ie it prints the custom message next to the field when I submit, but it always puts the internal binding message "The providerId field is required" for the dropdown list. What do I have to do to change the message to the custom added message. This happens to all my dropdownlists in the code! The ProviderId is a required field in the DB, and henc im seeing the message but how do I override it to show a custom message? Maybe this is a simple fix, but I am a total noob(2 hours) to MVC and want to fix this

"Board cannot be empty"

EDITED : the field is ProviderID

I guess, you are using database-first (or model-first) approach and so you have an edmx file and the corresponding .Designer.cs file. In this last file, you probably have something like this:

[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)]
[DataMemberAttribute()]
public global::System.Int32 ProviderID

Here the type int is not nullable and the property has the metadata attribute IsNullable=false . That's why, ASP.NET MVC gives the default error message.

A simple workaround is to set as not required the field on the db, then update the model. After that, you should see in your .Designer.cs something like this:

[EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=true)]
[DataMemberAttribute()]
public Nullable<global::System.Int32> ProviderID

Now, you can see your custom message "Board cannot be empty".

A better approach (instead of changing db and model) is to delete from your controller if (courselist.ProviderID == null)... and to use metadata. Here's a snippet:

[MetadataType(typeof(YourEntityMetaData))]
public partial class YourEntity
{

}

public class YourEntityMetaData
{   
   [Required(ErrorMessage = "Board cannot be empty")]
   public int ProviderID   { get; set; }    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM