How to set state of dropdownlistfor default value

2019-04-01 04:53发布

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条回答
【Aperson】
2楼-- · 2019-04-01 05:07

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>
查看更多
何必那么认真
3楼-- · 2019-04-01 05:24

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" })
查看更多
登录 后发表回答