SelectList 不返回文本值 returns ID

SelectList not returning the value of text only returns ID

我是 asp net core 的新手,我正在尝试实现一个 select 列表,同时将值从视图传递到控制器。其他一切都很好,我面临的唯一问题是只有 ID 被传递给控制器​​,而不是 text/name。 有人能告诉我哪里出错了吗?下面是我的代码。

查看代码段

<div class="form-group">
    <label>Financial Year</label>
    <select asp-for="FinancialYear" asp-items="ViewBag.FinancialYear" class="selectpicker" data-dropup-auto="false" data-size="5">
    </select>
</div>

模型片段

public class VMOM
{ 
    public int FinancialYear { get; set; } 
}

public class VMDropDown
{
    public int ID { get; set; }
    public string Text { get; set; }
}

控制器代码段

[HttpGet]
public IActionResult Create()
{
    VMOM vmOM = new VMOM();
    ViewBag.FinancialYear = new SelectList(GetFinancialYearList(), "ID", "Text", 0).ToList();
    return View(vmOM);
}

[HttpPost]
public IActionResult Create(VMOM vmOM)
{
    return View(vmOM);
}

private List<VMDropDown> GetFinancialYearList()
{
    List<VMDropDown> vmDropdowns = new List<VMDropDown>
    {
        new VMDropDown() { ID = 1, Text = "2019" },
        new VMDropDown() { ID = 2, Text = "2020" }
    };
    return vmDropdowns;
}

action 方法中收到的值的 SS;请注意,在 Financial Year 中,仅显示年份 ID 而不是文本值,即 2020

最简单的方法是将 ID 值更改为与文本相同的值。

List<VMDropDown> vmDropdowns = new List<VMDropDown>
{
    new VMDropDown() { ID = 2019, Text = "2019" },
    new VMDropDown() { ID = 2020, Text = "2020" }
};

如果你不介意一点点javascript,你可以轻松实现你想要的。

我们添加了一个隐藏的输入字段,其值在 select 更改时更新。 所以当我们提交表单时,隐藏输入的值将被提交并与我们的模型绑定(见下面的截图)。

剃须刀:

<form asp-action="Post" method="post">
    <select class="form-control" asp-items="@ViewBag.List" asp-for="@Model.Id" id="FYear">
    </select>
    <input type="hidden" id="FYearText" asp-for="@Model.Year" readonly="readonly" hidden/>
    <button type="submit" class="btn btn-success">Submit</button>
</form>

型号

public class VMOM
{
    public int Id { get; set; }
    public string Year { get; set; }
}

控制器:

[HttpGet]
public IActionResult Index()
{
    var data = new List<VMOM> {
        new VMOM { Id = 1, Year = "2018" },
        new VMOM { Id = 2, Year = "2019" },
        new VMOM { Id = 3, Year = "2020" },
        new VMOM { Id = 4, Year = "2077" }
    };

    ViewBag.List = new SelectList(data, "Id", "Year");

    return View("Index", new VMOM());
}

JS

$(document).ready(function(){
    $("#FYear").on("change", function(){
        $("#FYearText").val($(this).find("option:selected").text());
    });
});

结果:

P.S,为了简洁起见,我在此示例中使用 jQuery。