Вот пример, основанный на вашем требовании. Класс 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.cs html:
@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>
Результат этого демо: