【问题标题】:Be able to add and item in a drop down list if it is not present如果不存在,则能够在下拉列表中添加和项目
【发布时间】:2020-02-23 09:00:11
【问题描述】:

我有一个包含城市名称的下拉列表。如果列表中不存在,我希望用户能够添加他们的城市,然后必须保留在数据库中? 我正在使用 ASP.NET 核心

【问题讨论】:

  • 先查数据库保存城市再更新下拉列表

标签: list asp.net-core dropdown


【解决方案1】:

这是根据您的要求提供的示例。 City.cs 类:

 public class City
{
    [Key]
    public int Id { get; set; }
    [Required]
    public string CityName { get; set; }
}

控制器:

  public IActionResult Index()
    {
        ViewBag.Cities = new SelectList(_context.City, "Id", "CityName");
        return View();
    }
    [HttpPost]
    public IActionResult Index(City city)
    {
        if (!ModelState.IsValid || _context.City.Where(x => x.CityName == city.CityName).Count() > 0)
        {
            ViewBag.Cities = new SelectList(_context.City, "Id", "CityName");
            return View();
        }
        _context.City.Add(city);
        _context.SaveChanges();
        return RedirectToAction("Index");
    }

Index.cshtml:

@model WebApplication_core.Models.City
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h1>SelectIndex</h1>

<select asp-for="Id"
        asp-items="@ViewBag.Cities">
    <option>Please select one</option>
</select>
<h4>add your city</h4>
<form asp-controller="Home" asp-action="Index">
    <div class="form-group">
        <label asp-for="CityName" class="control-label"></label>
        <input asp-for="CityName" class="form-control" />
        <span asp-validation-for="CityName" class="text-danger"></span>
    </div>
    <input type="submit" value="submit" />

</form>

此演示的结果:

【讨论】:

  • 这非常有帮助!!!非常感谢您的友好帮助。我会将此标记为答案!亲切的问候,卢克。
猜你喜欢
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 2015-06-24
  • 2020-10-12
  • 1970-01-01
  • 2017-12-10
  • 2021-07-02
  • 2018-02-02
相关资源
最近更新 更多