I need to make a drop-down in Razor that can allow the users to type in too so users have the option to select something from the down list and if the value they want to select from drop-down does not exist in drop down then they can type in that value and once they type in, the value gets stored in the database.
You can achieve it via the select2 plugin, refer to the following sample:
In this sample, you will use a DropDownList to select the customer's name, if the name does not exist, it will add a new option in the DropDownList. After submitting the form, in the Post method, you can get the name and check whether it is existed in the database or not, then based on the result to insert the new name into database.
Controller:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public ApplicationDbContext _dbContext { get; set; }
public HomeController(ILogger<HomeController> logger, ApplicationDbContext applicationnDbContext)
{
_logger = logger;
_dbContext=applicationnDbContext;
}
public IActionResult CustomIndex()
{
SelectList customers = new SelectList(_dbContext.Customers.ToList(), "CustomerId", "Name");
ViewBag.Select = customers;
return View();
}
[HttpPost]
public IActionResult CustomIndex(string Name)
{
//check whether the name exist in the database,
//based on the result, insert the new name into database.
return View();
}
CustomIndex View:
@model TestMVC.Models.Customer
@{
ViewData["Title"] = "CustomIndex";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>CustomIndex</h1>
<form method="post" asp-controller="Home" asp-action="CustomIndex">
<select id="ddlCustomers" name="Name" asp-items="ViewBag.Select">
<option value="0">--Select Customer--</option>
</select>
<br />
<br />
<input type="submit" value="Submit" />
</form>
@section Scripts{
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#ddlCustomers").select2({
tags: true,
createTag: function (params) {
return {
id: params.term,
text: params.term,
newOption: true
}
},
templateResult: function (data) {
var $result = $("<span></span>");
$result.text(data.text);
if (data.newOption) {
$result.append(" <em>(new)</em>");
}
return $result;
}
});
});
</script>
}
The result as below:
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion