Home > database >  How to bind id in datalist form
How to bind id in datalist form

Time:05-25

I have some datalist in razor page:

<form asp-page-handler="AddUser" method="post">
<input type="search" list="datalistusers" id="searchid" name="userName" placeholder="Введите имя.." />
<button type="submit" >
     Добавить
</button>
     <datalist id="datalistusers">
     @foreach (var user in @Model.Course.UserCourses)
     {
         <option>@user.User.Name</option>
     }
</datalist>
</form>

When I sumbit form in method I get only username. How can i bind user id in this form?

Codebehind:

public IActionResult OnPostAddUser(string username,string userid)
{
    //some action
    //done
    return Page();
}

CodePudding user response:

Here you only passed/ bind username from your form, that's why you're only getting username in the controller action. you've to bind userid also in your form. like bellow

     <form asp-page-handler="AddUser" method="post">
            <input type="search" list="datalistusers" id="searchid" name="userName" placeholder="Введите имя.." />
            <input type="text"  id="userid" name="userid" placeholder="Enter User Id" />
            <button type="submit" >
                Добавить
            </button>
            <datalist id="datalistusers">
                @foreach (var user in @Model.Course.UserCourses)
                {
                    <option>@user.User.Name</option>
                }
            </datalist>
        </form>

CodePudding user response:

Maybe this is what you want?

You can add another input and set it to type="hidden", and then use JS to match the userid corresponding to the userName you selected.

Below is my test code:

<form asp-page-handler="AddUser" method="post">
        <input type="search" list="datalistusers" id="searchid" name="userName" placeholder="Введите имя.." />
        <input type="hidden" id="userid" name="userid" />
        <button type="submit" >
            Добавить
        </button>
        <datalist id="datalistusers">
                <option>TestName1</option>
                <option>TestName2</option>
                <option>TestName3</option>
        </datalist>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("#searchid").change(function() {
    // Add loop over Model to match id
    if ($("#searchid").val() == "TestName1") 
    {
        $("#userid").val("1");
    } 
    else if ($("#searchid").value == "TestName2") 
    {
        $("#userid").val("2");
    } 
    else 
    {
        $("#userid").val("3");
    }
});
</script>

Test Result: enter image description here

  • Related