i am new on asp.net razor page
this is my Html
<div >
<div >
<select id="itemslist" name="itemName" asp-items="Model.Itemslist">
<option value="SSS"></option>
</select>
<input type="hidden" name="itemName"asp-for="Expiree.ItemName" />
<br />
<br />
@if (ViewData["Message"] != null)
{
<script type="text/javascript">
window.onload = function ()
{
alert("@ViewData["Message"]");
};
</script>
}
</div>
this my script section
@section scripts
{
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/dist/js/select2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#itemslist").select2();
});
$("body").on("change", "#itemslist", function () {
$("input[name=itemName]").val($(this).find("option:selected").text());
});
</script>
}
this my page model
namespace SparkAuto.Pages.Expire
{
public class CreateeModel : PageModel
{
private readonly ApplicationDbContext _db;
public CreateeModel(ApplicationDbContext db)
{
_db = db;
}
public SelectList Itemslist { get; set; }
[BindProperty]
public Expiree Expiree { get; set; }
public IActionResult OnGet()
{
this.Itemslist = new SelectList(_db.Items, "Id", "Name");
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
_db.Expiree.Add(Expiree);
await _db.SaveChangesAsync();
return RedirectToPage("Index");
}
}
}
finally this my error i get Null in itemName in database
this a screenshot from searchable select2 dropdown list i use
I search in 3K items in this dropdown list and need to push the item name after selection
CodePudding user response:
You can use select to bind id of Expiree
,and bind ItemName
with hidden input:
Expire:
public class Expiree {
public int ItemId { get; set; }
public string ItemName { get; set; }
}
html:
<select id="itemslist" asp-for="Expiree.ItemId" asp-items="Model.Itemslist">
<option value="SSS"></option>
</select>
<input type="hidden" asp-for="Expiree.ItemName" />
js:
@section scripts
{
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/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/[email protected]/dist/js/select2.min.js"></script>
<script type="text/javascript">
$(function () {
$("#itemslist").select2();
});
$("body").on("change", "#itemslist", function () {
$("#Expiree_ItemName").val($(this).find("option:selected").text());
});
</script>
}