0
  public static IList<MyTestStatus> CreateMyTestStatusList()
                    {
                        List<MyTestStatus> status = new List<MyTestStatus>();
                        status.Add(new MyTestStatus() { Name = "1" });
                        status.Add(new MyTestStatus() { Name = "2" });
                        status.Add(new MyTestStatus() { Name = "3" });
                        status.Add(new MyTestStatus() { Name = "4" });
                        return status.ToList();
                    }

@Html.DropDownListFor(model => model.MyTestStatus, new SelectList(Model._MyTestViewModel.MyTestStatus), "Select.....", new { @class = "form-control"})

i have this code for dropdownlistfor i want the selected value by default to be "4" or the selected value which the user select,i used jQuery


$("#MyTestStatus").val("4");

when the page load is displaying "4" as i want,but in update the value will always display as "4" even if select a different value.

Mhmd
  • 38
  • 2
  • 8

3 Answers3

0

You should set your defaults to model.MyTestStatus model property. That's from where DropDownListFor helper get selected value.

Just populate this property in your controller.

teo van kot
  • 12,350
  • 10
  • 38
  • 70
  • Still Not Working,in my view i was trying to check if nothing selected '@if (Model.MyTestStatus!=null) { @Model.MyTestStatus } else { @ }' – Mhmd Apr 28 '16 at 16:51
  • @Mhmd please add your controller and more View code to question – teo van kot Apr 28 '16 at 17:38
0

Since you are binding it a property using the DropDownFor() helper method, it will automatically map it to the MyTestStatus property on your Model. If this isn't being set properly, you could consider setting it when building your Model initially.

The SelectList class does support a constructor for it's default selection, but it will likely be overridden if a value is present on your Model :

new SelectList(Model._MyTestViewModel.MyTestStatus,"4")

Alternatively, you could use the DropDown() helper (instead of the model-bound DropDownFor() one) which would ignore the Model value and just use your selection :

@Html.DropDownList("MyTestStatus", new SelectList(Model._MyTestViewModel.MyTestStatus,"4"), "Select.....", new { @class = "form-control"})
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0
@Html.DropDownListFor(model => model.MyTestStatus, new SelectList(Model._MyTestViewModel.MyTestStatus,"Name","Name","4"), "Select.....", new { @class = "form-control"})

Finally..this is working fine..thank you

Mhmd
  • 38
  • 2
  • 8
  • Sorry to be harsh but this is nonsense. Your property `MyTestStatus` is `IList` and you cannot bind a ` –  Apr 28 '16 at 21:43