在MVC C#中填充数据库中的值以下拉

时间:2015-12-10 14:40:22

标签: c#

我在表中有国家名称,其ID为image.I我希望使用MVC模型在视图页面(HTML)中创建一个下拉列表,其中国家名称应使用C#编码填充在其中。

image

1 个答案:

答案 0 :(得分:2)

您可能希望在模型上设置一个可以绑定到下拉列表的属性。我用一个简单的例子来说明你的数据:

创建一个表示国家/地区表的类:

$currentDate = new DateTime('now'); //current date
$b_issued    = new DateTime('2015-12-08 10:00:00');  //date when the book was issued
$b_time      = 5; //number of days for which has been given a book
$interval    = $b_issued->diff($currentDate);
$b_left_days =  $b_time - $interval->d;

if ($b_left_days == 2) {
  //...
}

现在填充表格中的数据列表,您应该通过调用数据库来执行此操作:

public class country
{
    public string countries { get; set; }
    public int id { get; set; }
}

绑定数据有多种方法,但简单的方法如下:

var countries = new List<country>();
countries.Add(new country() { id = 1, countries = "ind" });
countries.Add(new country() { id = 2, countries = "usa" });
countries.Add(new country() { id = 3, countries = "uk" });
countries.Add(new country() { id = 4, countries = "pak" });
countries.Add(new country() { id = 5, countries = "britan" });

在您的视图中,您将要绑定刚刚创建的对象。在这种情况下,它只是模型。

var countriesList = new List<SelectListItem>(
                countries.Select(_ => new SelectListItem() { 
                    Text = _.countries, 
                    Value = _.id.ToString() }
                )
            );
return View(countriesList);
// You can also add countriesList as a property on a bigger model

希望这有帮助,祝你好运!