How to bind DataTable to @Html.DropDownListFor in asp.net MVC3

前端 未结 3 1617
粉色の甜心
粉色の甜心 2021-01-27 20:09

I have a DataTable which looks like below:

TOTAL_CODE COD_NAME AP0001 School AP0002 Hospital AP0003 Airport A

3条回答
  •  悲哀的现实
    2021-01-27 20:25

    this is one way to do it.

    Edit:
    
     //you can take this as a Sex Model
                public class Sex {
                    public string gender { get; set; }
                    public string shortname { get; set; }
                }
                public List SexList() {
                    //if you have your sex model in the database , you can get it here
    
                    //I have a static content below, just to show you how you can manuplate the sex model,
                    List s = new List() { new Sex() { gender = "Male", shortname = "M" }, new Sex() { gender = "Female", shortname = "F" } };
    
                    List items = new List();
                    //go through the sex model and populate you selectlist items
                    foreach (Sex sex in s) {
                        SelectListItem item = new SelectListItem();
                        item.Text =sex.gender;
                        item.Value =sex.shortname;
                        items.Add(item);
                    }
                    return items;
                }
    

    On your controller

    [HttpGet]
    public ActionResult DetailAdd()
    {
        Profile profile = new Profile();
        //set the sex types
        profile.SexList=SexList();
    
        return View(profile);
    }
    

    on your view

    @model Kery.Models.Profile
    @{
        ViewBag.Title = "DetailAdd";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    

    Please select your sex type: @Html.DropDownListFor("name",Model.SexList)

提交回复
热议问题