ASP.Net MVC5 中 DropDownlist 的问题

Difficulties with DropDownlist in ASP.Net MVC5

我正在为 dropdownlist 苦苦挣扎,在网上尝试了几种方法,但都失败了,将显示我尝试过的方法。

Objective 创建带有日期、参考...和国家/地区的收据。国家是必需的,应该是一个下拉列表。

因此 Table 用于 收据("ID, Name, Date, Address, City, CountryList).

接收模型

public class TransactionModel
{
    public int ID { get; set; }
    public int Name{ get; set; }
    public DateTime Date { get; set; }
    public string Address { get; set;}
    public string City { get; set; }
    public CountryList CountryList { get; set; }
}

public class ApplicationDbContext : DbContext
{
    public DbSet<RecieptModel> Reciepts { get; set;}
    public DbSet<CountryList> coutryList { get; set; }
}

国家列表

public class CountryList
{
    public byte Id { get; set; }

    public enum Country
    {
        Germany,
        US,
        UK
    }
}

控制器

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,Date,City,CountryList")] Reciepts reciepts)
{
    if (ModelState.IsValid)
    {
        db.Reciepts.Add(reciepts);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(reciepts);
}

查看

<div class="form-group">
    @Html.LabelFor(model => model.CountryList, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EnumDropDownListFor(model => model.CountryList)
        @Html.ValidationMessageFor(model => model.CountryList)
    </div>
</div>

这失败了我找了几个例子,我试图在不使用 javascript 的情况下做到这一点。最后,我只想学习如何实现下拉列表并将其保存到我尝试在 MVC5 中实现失败的方法的数据库分配。

我建议您添加一个 html 扩展方法来实现通用枚举器的下拉列表。看看this answer.

您绑定国家/地区的观点略有变化

这其实是你写的

 @Html.EnumDropDownListFor(model => model.CountryList)

更改需要在你的国家列表中添加名称属性(它必须是你在你的模型中使用的ID),所以它必须是这样来维护国家列表值

@Html.DropDownListFor(model => model.CountryList.Id, new SelectList(model => model.CountryList)

因为每个 HTML 控件都需要唯一的标识符