Oxygen
Oxygen

Reputation: 871

Selected string value of select not posting in asp.net MVC core 3.0

I have a string property in my model defined as

 [Required]
 [Display(Name = "Day Of Week")]
 public string DayOfWeek { get; }

Need to bind a dropdown for this so initiated ViewData as

var dayoftheweeks = new List<dynamic>() {
                          new  { DayOfWeek= "Monday"},
                          new { DayOfWeek="Tuesday"},
                          new { DayOfWeek="Wednesday"},
                          new { DayOfWeek="Thursday"},
                          new { DayOfWeek="Friday"},
                          new { DayOfWeek="Saturday"},
                          new { DayOfWeek="Sunday"}
                        };

        ViewData["DayOfWeek"] = new SelectList(dayoftheweeks, "DayOfWeek", "DayOfWeek", dayoftheweek);

and on the view it is implemented as

<select asp-for="DayOfWeek" class="form-control" asp-items="ViewBag.DayOfWeek"></select>

It binds the dropdown correctly but when I post the form DayOfWeek property comes as a null.

Confirmed that this selects select list options as a Value property rendered to it too. This is how it renders on page

<option value="Monday">Monday</option>

However I have used dropdown in another page where selected value is integer field. There it is posting selected value. I wonder if this is only with string selected Value.

Can you please guide if I am missing anything?

Updated It started working. Initially when there was a problem I had defined a property as

 [Required]
 [MaxLength(150)]
 [Display(Name = "Day Of Week")]
 // Comment statement
 public string DayOfWeek { get; set; }

To make it work, I just moved the comment part above of all anotations as

// Comment statement
 [Required]
 [MaxLength(150)]
 [Display(Name = "Day Of Week")]
 public string DayOfWeek { get; set; }

I still dont know the reason why comments placement make an impact.

Upvotes: 0

Views: 72

Answers (1)

navid faridi
navid faridi

Reputation: 331

I suggest to you to define an enum for day of week such as this :

public enum DayOfWeek : byte
    {
        Monday = 0,
        Tuesday = 1,
        Wednesday = 2,
        Thursday = 3,
        Friday = 4,
        Saturday = 5,
        Sunday = 6
    }

and then in view use this select same as shown below :

<select asp-for="DayOfWeek" asp-items="@Html.GetEnumSelectList<DayOfWeek>()" class="form-control"></select>

Upvotes: 0

Related Questions