Return Value From a SelectList

Roger Porter 41 Reputation points
2021-08-03T17:44:06.953+00:00

Hi,

I have an ASP.Net Core MVC View which has a various tabs / controls. On one tab I have a SelectList and an Anchor tag next to it. All I am trying to do is call an Action in the Controller with the selected value so I can create a new entry in another model but I don't know how to pass the selected value.

Unfortunately I am relatively new to ASP.Net Core MVC.

Any help please,

Thanks

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

Answer accepted by question author
  1. Anonymous
    2021-08-11T07:53:51.367+00:00

    Hi @Roger Porter ,

     <form id="CustomerDetails" asp-controller="CustomerDetails" asp-action="UpdateCustomer" method="post" class="mt-3">     
    <select id="drpUserList" asp-items="@(new SelectList(Model.users, "Id", "FullName"))" class="selectpicker col-offset-1"></select>    
    <a class="btn btn-primary" asp-controller="CustomerDetails" asp-action="AddUserToList" asp-route-???><span class="fas fa-user-plus"></span></a>    
    

    I basically want to call the AddUserToList action passing the UserID from the selectlist. I can't add the form tag because it is already in one.
    I tried to add the form tag just covering the first tab which worked but then my tab select stopped work.
    Been searching all day for a solution just don't seem to be able to either find or understand.

    Based on your code and description, you want to use the anchor tag to navigate to another view and transfer parameters. If that is the case, you could refer the following sample:

    use JQuery to get the selected user id, then change the anchor tag href attribute.

    <div class="row">  
        <div class="col-md-4">  
            <form id="CustomerDetails" asp-controller="CustomerDetails" asp-action="UpdateCustomer" method="post" class="mt-3">  
                <select id="drpUserList" asp-items="@(new SelectList(Model.users, "Id", "FullName"))" class="selectpicker col-offset-1"></select>  
                <a class="btn btn-primary" id="hyperlink" asp-controller="CustomerDetails" asp-action="AddUserToList"><span class="fas fa-user-plus"></span></a>  
            </form>  
        </div>  
    </div>   
     @section Scripts {  
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
    
        <script type="text/javascript">  
            $(function () {  
                $("#drpUserList").change(function () {  
                    //add the parameter  
                    var newurl = $("#hyperlink").attr("href") + "/?userid=" + $(this).val();  
                    //change the hyperlink href attribute.  
                    $("#hyperlink").attr("href", newurl);  
                });  
            });  
        </script>  
    }  
    

    The result as below:

    122210-1.gif


    If the answer is helpful, please click "Accept Answer" and upvote it.
    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

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. AgaveJoe 30,491 Reputation points
    2021-08-03T23:29:48.137+00:00

    My best guess is you want to do an AJAX request and a partial page refresh.

    namespace MvcDemo2.Controllers
    {
        public class ViewModel
        {
            public int OptionId { get; set; }
            public List<SelectListItem> Options { get; set; }
        }
        public class HomeController : Controller
        {
            private readonly ILogger<HomeController> _logger;
    
            public HomeController(ILogger<HomeController> logger)
            {
                _logger = logger;
            }
    
            [HttpGet]
            public IActionResult Index()
            {
                ViewModel vm = new ViewModel();
                vm.Options = PopulateOptions();
    
                return View(vm);
            }
    
            [HttpGet]
            public IActionResult AddUserToList(string Id)
            {
                return Ok(new { message = $"Added User {Id}" });
            }
    
            public List<SelectListItem> PopulateOptions()
            {
                List<SelectListItem> options = new List<SelectListItem>();
                for(int i = 1; i <= 10; i++)
                {
                    options.Add(new SelectListItem() { Value = $"{i}", Text = $"Option {i}" });
                }
                return options;
            }
        }
    }
    

    The View has a little JavaScript/jQuery app that a fetches an action when the select element changes. The action results are written to the results div in the script.

        @model MvcDemo2.Controllers.ViewModel
        @{
            ViewData["Title"] = "Home Page";
        }
    
        <div>
            <select asp-for="OptionId" asp-items="Model.Options">
                <option value="">--Select--</option>
            </select>
        </div>
        <div id="result">
    
        </div>
    
        @section scripts{ 
        <script>
            $("#OptionId").change(function () {
                fetch('/Home/AddUserToList/' + $(this).val())
                    .then(response => response.json())
                    .then(data => $('#result').text(data.message));
            });
        </script>
        }
    
    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.