Как связать DataTable с @ Html.DropDownListFor в asp.net MVC3 - PullRequest
0 голосов
/ 18 декабря 2011

У меня есть DataTable, который выглядит следующим образом:

TOTAL_CODE COD_NAME Школа AP0001 Больница AP0002 Аэропорт AP0003 AP0004 Дом

Я новичок в ASP.NET MVC3 и не могу понять, как связать DataTable с моим элементом управления DropDownListFor.

PS: у меня есть модель, как показано ниже:

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

<P>Please select your sex type: @Html.DropDownListFor(..............)</p>

Модель:

public class Profile
{
    public IEnumerable<SelectListItem> SexList { get; set; }
}

Контроллер:

[HttpGet]
public ActionResult DetailAdd()
{
    System.Data.DataTable _dtJikchaekList = _bp.DtReturnS(false
     , "CHP_AJAX_CODEHELPER"
     , "JJ"
     , ""
     , "0"
     );
    return View();
}

Ответы [ 3 ]

2 голосов
/ 18 декабря 2011

это один из способов сделать это.

Edit:

 //you can take this as a Sex Model
            public class Sex {
                public string gender { get; set; }
                public string shortname { get; set; }
            }
            public List<SelectListItem> 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<Sex> s = new List<Sex>() { new Sex() { gender = "Male", shortname = "M" }, new Sex() { gender = "Female", shortname = "F" } };

                List<SelectListItem> items = new List<SelectListItem>();
                //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;
            }

На вашем контроллере

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

    return View(profile);
}

на ваш взгляд

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

<P>Please select your sex type: @Html.DropDownListFor("name",Model.SexList)</p>
0 голосов
/ 01 марта 2018

Мне показалось, что все другие подходы очень запутаны, поэтому я сделал это, на мой взгляд, и, похоже, работает просто отлично.Ноль - это индекс столбца для таблицы.Я использую vb.net

<select>
    @Code
        For Each row In Model.dataTable.Rows
            @<option>@row(0)</option>
        Next
    End Code
</select>
0 голосов
/ 29 января 2013
 <http://dotnetpools.com/Article/ArticleDetiail/?articleId=48&title=Binding%20Dropdownlist%20In%20MVC3%20Using%20C#t;>

## razor ##

        @Html.DropDownList("Country", new SelectList(Model.CountryList, "Value", "Text", Model.CountryList.SelectedValue), new { @id = "ddlist", @data_role = "none", style = "color: #fff; background-color: #fff; font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #333333; margin-left:3px; width:100%; height:20px;" })


## model ##

         public class somename
          {
           public SelectList CountryList { get; set; }
          }
           public class Country
            {
                public string ID { get; set; }
                public string Name { get; set; }
            }



## Controller ##

           public ActionResult index()
            {
              List<Country> objcountry = new List<Country>();
              objcountry = GetCountryList();
              SelectList objlistofcountrytobind = new SelectList(objcountry, "ID", "Name", 0);
              model.CountryList = objlistofcountrytobind;       
              return View(model);
            }


          [HttpPost]
          public ActionResult Analyze(AnalyzeModels model)
           {
              List<Country> objcountry = new List<Country>();
              objcountry = GetCountryList();
              SelectList objlistofcountrytobind = new SelectList(objcountry, "ID", "Name", 0);
              model.CountryList = objlistofcountrytobind;
              return View(model);
           }


            **************************************************
## function for GetCountryList##
            public List<Country> GetCountryList()
            {
                DataTable reportDetailsTable = objCommon.GetDetails("tablename");

                List<Country> objcountrty = new List<Country>();
                int s = reportDetailsTable.Rows.Count;
                for (int i = 0; i < s; i++)
                {
                    string d1 = reportDetailsTable.Rows[i][1].ToString();
                    string d2 = reportDetailsTable.Rows[i][10].ToString();
                    objcountrty.Add(new Country { ID = d1, LName = d2 });
                }
                return objcountrty;
            }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...