关于下拉列表,我在基本问题上遇到了很多问题,我做了很多在stackoverflow中描述的方法,而所有方法都没有用,我将总结这样的代码。我只想简单地创建一个保存到数据库的下拉列表。
这就是我所做的 DefaultModel
public class DefaultModel
{
public int Id {get; set;}
//other things
public CountryList SelectedCountry {get; set;}
}
public DefaultDbContext : DbContext
{
public DbSet<DefaultModel> DefaultModels {get; set;}
public DbSet<CountrtyList> CountryLists {get; set;}
}
国家列表模型
public class CountryList
{
public byte Id {get; set;}
public string name {get; set;} //country name
public DefaultModel DefaultModel {get; set;}
}
ViewModel
public class CountryListViewModel
{
public byte Id {get; set;}
public List<CountryList> CountryList {get; set;}
DefaultController 不是主控制器
private DefaultDbContext = db;
public HomeController
{
db = new DefaultDbContext;
}
public ActionResult Index()
{
var countryLists= _context.CountryLists.ToList();
var viewModel = new CountryListViewModel
{
Default = new DefaultModel(),
CountryLists = countrylists
};
return View(viewModel);
}
查看
@model Default.ViewModels.CountryListViewModel
<div class="form-group">
@Html.LabelFor(model =>
model.TransactionModel.SelectedCountry.CountryLists
, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(
model => model.TransactionModel.SelectedCountry.CountryLists
, new SelectList(Model.CountryList, "Id, Name"), "Select Country")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
迁移添加国家/地区
Sql("INSERT INTO COUNTRYLISTS (Id, Name) VALUES(1, UK)");
错误
System.NullReferenceException: “对象引用未设置为对象的实例。”
我只是想从头开始学习如何在MVC5中创建一个下拉列表,我浪费了时间,并且多次尝试都失败了。我看到使用无法使用的方法的教程,我不知道哪里有问题或应该怎么做。
答案 0 :(得分:0)
模式
textFieldDidEndEditing
控制器
`
namespace WebApp.Models
{
public class CountryList
{
public byte Id { get; set; }
public string name { get; set; } //country name
//public DefaultModel DefaultModel { get; set; }
}
public class CountryListViewModel
{
public string CountryLists { get; set; }
public List<CountryList> CountryList { get; set; }
}
}
查看
List<CountryList> countrylists = new List<CountryList>();
//I am using static list items. Just change this to get data from entity framework;
countrylists.Add(new CountryList //pass one default list Item here so that your list is never null.
{
Id = 0,
name = "Select Country"
});
countrylists.Add(new CountryList
{
Id = 1,
name = "UK"
});
var viewModel = new CountryListViewModel
{
//Default = new DefaultModel(),
CountryList=countrylists,
CountryLists="Country List"
};
return View(viewModel);`