簡體   English   中英

ASP.Net MVC5中DropDownlist的困難

[英]Difficulties with DropDownlist in ASP.Net MVC5

我在dropdownlist上嘗試了幾種在線嘗試的方法,所有嘗試失敗的方法都會顯示我嘗試過的方法。

目的創建包含日期,參考...和國家/地區的收據。 國家/地區為必填項,應為下拉列表。

所以表收據 (“ID,姓名,日期,地址,城市,CountryList)。

RecieptModel

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中失敗的方法的數據庫分配中。

我建議您添加一個HTML擴展方法,該方法為通用枚舉器實現dropdownlist。 看看這個答案

綁定國家/地區的視圖稍有變化

這實際上是你寫的

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

需要進行更改以在國家列表中添加name屬性(它必須是您在模型中采用的ID),因此必須這樣才能保持國家列表的值

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

因為每個HTML控件都需要唯一的標識符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM