1

How to set state of dropdownlist for default value to the one stored in database in edit view when using auto generated models via edmx (not created manually).

Here is my code :

View :

 @Html.DropDownListFor(model => model.site_id, new SelectList(ViewBag.site_id, "id", "name"), "Select Any", new {@class="form-control",required="required",autofocus="autofocus" })

Controller :

  ViewBag.site_id = dbContext.axi_sites;

Been looking for the solution for quite a while, none match to the exact requirement.

2
  • post the code where you making SelectList in action Apr 18, 2014 at 5:40
  • Populate the selected value in model.site_id, rest will be taken care off
    – Satpal
    Apr 18, 2014 at 5:58

2 Answers 2

2

Why should we bother. We can use jquery too.

add jquery 1.10.3 in your code. and code below in your page where you want dropdownlistfor selected value

write in View part

<script  type="text/JavaScript">
   $(document).ready(function () {
     $('#site').val(@Model.site_id);
  });
</script>

@Html.DropDownListFor(model => model.site_id, new SelectList(ViewBag.site_id, "id", "name"), "Select Any", new {@class="form-control",required="required",autofocus="autofocus",id="site" })
1
  • Tried the solution posted by @shivoham and it worked, thanks :) have been looking for the same since a long time.
    – imsheth
    Apr 21, 2014 at 12:24
1

C# code:

public class MyClass {
    public int Id { get; set; }
    public string Name { get; set; }
}


var list = new[] {   
    new MyClass { Id = 1, Name = "Name1" }, 
    new MyClass { Id = 2, Name = "Name2" }, 
    new MyClass { Id = 3, Name = "Name3" } 
};

var selectList = new SelectList(list, "Id", "Name", 2);
ViewBag.DDL = selectList;

In View:

@Html.DropDownListFor(model => model.site_id,
                     ViewBag.DDL as SelectList, 
                     "Select Any", 
                     new {@class="form-control",required="required",autofocus="autofocus" })

Html Output:

<select id="site_id" name="site_id" required="required" class="form-control">
    <option value="1">Name1</option>
    <option selected="selected" value="2">Name2</option>
    <option value="3">Name3</option>
</select>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.