0

I have a page with the model below

@model Justice.Domain.MyClasses.Employeekronosdisplay

I am using the dropdownlistfor below

@Html.DropDownListFor(m => m.GetEmpHoursDateRange.selectedEmplhoursdate, 
                     Model.GetEmpHoursDateRange.EmphoursdateSelectList,
                     new { id = "procDateId" })        

Here is the model I am using

public class Employeekronosdisplay
{
    public Setemployeehoursdate GetEmpHoursDateRange { get; set; }
}

Here is another model I use to get all my data to the view.

public class Setemployeehoursdate
{
    public string selectedEmplhoursdate { get; set; }
    public IEnumerable<SelectListItem> EmphoursdateSelectList { get; set; }
}

Problem : This is a dropdown for a date and I expect that the date I pass to the selectedEmplhoursdate property is what should be the default in my dropdown. I am able to pass the right date without any problem to selectedEmplhoursdate

However the dropdown is not showing the selectedEmplhoursdate I specify. It is showing another date which seems to be the first item in my selectList

How can I resolve this? I want to be able to pass a default date.

Maksim Simkin
  • 9,561
  • 4
  • 36
  • 49
Baba
  • 2,059
  • 8
  • 48
  • 81
  • 1
    Possible duplicate of [@Html.DropDownListFor how to set default value](http://stackoverflow.com/questions/23799091/html-dropdownlistfor-how-to-set-default-value) – Maksim Simkin Jan 12 '17 at 19:10

1 Answers1

0

Honestly, I've never been a fan of the Razor approach. Simply because when you have other data, you're forced to add dropdown data into a Model-View-View-Model since you can only pass a single model to a view.

So I would personally do:

<select id="Employee">
     <option>-- Please Choose --</option>
</select>

Then I would simply do jQuery, with an Ajax to populate and build the dropdown.

$(function () {
     buildDropdown($('#Employee'), '/Home/GetEmployee');
});

function buildDropdown(dropdown, action) {
     $.ajax({
         url: action,
         ...
         success: function(response) {
             var enumerable = JSON.parse(response);
             $.each(enumerable, function(index, option) {
                  dropdown.append($('<option></option>').val(option.Value).html(option.Label);
             }
         }
     });    
}

Something along those lines, that way it is reusable. Though it is a bit more verbose. Also, when you need to set a selected value, you could simply do: $('#Employee').val(content) which would set it to the default date.

Your specific problem can be remedied:

@Html.DropDownListFor(Model => 
     Model.Employee.Name, 
     Model.Employee.GetDateCollection, 
     Id = Model.Employee.DefaultDateRecord,
     " -- Please Choose -- ")
Greg
  • 11,302
  • 2
  • 48
  • 79
  • Thanks. It will be very tough for me to rewrite what I have. There should be a way of making the selectedvalue passed show up. – Baba Jan 12 '17 at 23:22