Solved

Required Error Message is not displaying as expected on a field that is a Dropdown List

Posted on 2014-03-24
4
299 Views
Last Modified: 2014-04-09
I have the following metadata for my model (just showing the one data table):

public class AppCatalog_DatabaseMetadata
    {
        [UIHint("MVC4PrimaryKey")]
        [DisplayName("ID")]
        public int databaseID { get; set; }
        [HtmlProperties(Size = 100, MaxLength = 100)]
        [Required(ErrorMessage = "* Database Name is required")]
        [DisplayName("Database Name")]
        [UIHint("MVC4String")]
        public string databaseName { get; set; }
        [DisplayName("Description")]
        [UIHint("MVC4TextBox")]
        [HtmlProperties(Rows = 5, Cols = 75, MaxLength = 1000)]
        [Required(ErrorMessage = "* Description is required")]
        public string databaseDescription { get; set; }
        [DisplayName("S1")]
        [UIHint("ServerType")]
        [Required(ErrorMessage = "* Server Type is required")]
        public int databaseServerTypeID { get; set; }
        public virtual AppCatalog_ServerType AppCatalog_ServerType { get; set; }
    }

Open in new window


I am using the built-in [Required] attribute.

Here are my Create actions in my controller:
        public ViewResult Create()
        {
            ViewBag.Title = "Application Catalog -> Database Catalog -> Add Database";
            SelectList slServerType = new SelectList(db.AppCatalog_ServerType, "servertypeID", "servertypeName");
            ViewBag.databaseServerTypeID = slServerType;
            return View();
        }

        //
        // POST: /DBCatalog/Create

        [HttpPost]
        public ActionResult Create(AppCatalog_Database appcatalog_database)
        {
            if (ModelState.IsValid)
            {
                //db.AppCatalog_Database.Add(appcatalog_database);
                //db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.databaseServerTypeID = new SelectList(db.AppCatalog_ServerType, "servertypeID", "servertypeName", appcatalog_database.databaseServerTypeID);
            return View(appcatalog_database);
        }

Open in new window


Here is a partial listing of my View:
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true, "", new { @class = "validation-summary-errors" }) 

    <fieldset>
        <div class="editor-field">
            @Html.Label("Server Type", new { @class = "editor-label" }) :
            @Html.DropDownList("databaseServerTypeID", "-- Choose Server Type --")
            <span class="error-msg">@Html.ValidationMessageFor(model => model.databaseServerTypeID)</span>
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.databaseName)
            <span class="error-msg">@Html.ValidationMessageFor(model => model.databaseName)</span>
        </div>

        <div class="editor-field">
            @Html.EditorFor(model => model.databaseDescription)
            <span class="error-msg">@Html.ValidationMessageFor(model => model.databaseDescription)</span>
        </div>

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

Open in new window


The problem is when I click Create without entering any data, I get the Required Error Messages on the Database Name field and Description Field but not the Server Type Field which is showing -- Choose Server Type -- .

When I enter a database name and description and hit Create, the Required message for the Server Type is displayed.

How do I get the Server Type Required message to display if -- Choose Server Type -- is displayed when Create is clicked?

Any help is greatly appreciated!
0
Comment
Question by:dyarosh
  • 3
4 Comments
 
LVL 27

Expert Comment

by:Sammy
ID: 39954244
try something like this

[Required(ErrorMessage = "* Server Type is required")]
[Range(0, int.MaxValue, ErrorMessage = "MESSAGE HERE")]
public int databaseServerTypeID { get; set; }

Open in new window


The property is of type int, you have to use a range as above to trigger the validation
0
 

Author Comment

by:dyarosh
ID: 39955981
I tried your suggestion but still couldn't get the required error message to display.  I even changed the range to be 1 to int.MaxValue.
0
 

Accepted Solution

by:
dyarosh earned 0 total points
ID: 39978423
I found the problem.  I had to change from DropDownList to DropDownListFor.  Now my error message displays if an option is not selected from the DropDownList before posting back to the server.
0
 

Author Closing Comment

by:dyarosh
ID: 39988232
Found the solution on my own.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now