ASP.Net MVC5中DropDownlist的困难

问题描述 投票:0回答:2

我正在努力与dropdownlist尝试在线的几种方法,所有失败将显示我尝试的方法。

目标创建一个包含日期,参考...和国家/地区的收据。国家/地区是必填项,应该是下拉列表。

所以收据表(“身份证,姓名,日期,地址,城市,国家名单)”。

收据模型

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; }
}

CountryList

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。最后,我只是想学习如何实现Dropdownlist并将其保存到我试图在MVC5中实现失败的方法的数据库。

c# asp.net asp.net-mvc-5 enumdropdownlistfor
2个回答
0
投票

我会提示你添加一个html扩展方法,为一般的enumarator实现dropdownlist。看看this answer


0
投票

There is slightly change in your view where you bind the Country

这实际上是你写的

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

更改需要在您的国家/地区列表中添加名称属性(它必须是您在模型中使用的ID),因此必须保持国家/地区列表值

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

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

© www.soinside.com 2019 - 2024. All rights reserved.