简体   繁体   中英

How to get the value from a dropdown button that uses @Html.DropDownListFor tag helper in ASP.NET CORE MVC

I have a dropdown button which populates the values using the HTML tag helper @Html.DropDownListFor The code for the button is:

<div class="col-sm-3" id="valueSetParent">
    @Html.DropDownListFor(model => model.Id, new SelectList(Model.Sets, "Id", "Name"), new { @class = "btn btn-sm btn-outline-secondary dropdown-toggle", @style = "font-color: white" })
</div>

I have a javascript function which requires the Id value of the option that is selected in the dropdown button.

function xyx=z(e, testId, Id) {
        e.stopPropagation();
        $('#Modal').data('test_id', testId).data('id', Id).modal('show');
    }

But when I run the code, the value of Id does not get sent to the function and shows NULL in this case. How do I make sure the Id of the selected value in the dropdown button is sent to the javascript function?

Do you mean you want to get the Id of selected item, new SelectList(Model.Sets, "Id", "Name") made the Id be Value,Name be Id of Selected Item.You can use $("select").val() or $("#Id").val() to get the Id in js rather than pass data to the function. Here is a demo:

Controller:

 public IActionResult DropDown() {
        DropDownModel dropDownModel = new DropDownModel();
        dropDownModel.Sets = new List<Set1> { new Set1 { Id="s1",Name="set1"},new Set1 { Id="s2",Name="set2"} };
        return View(dropDownModel);
    }

View:

<h1>DropDown</h1>
<div>
    @Html.DropDownListFor(model => model.Id, new SelectList(Model.Sets,"Id","Name"), new { @class = "btn btn-sm btn-outline-secondary dropdown-toggle", @style = "font-color: white" })
</div>
<div>
    <button onclick="selectId()">select</button>
</div>
@section scripts{ 
<script type="text/javascript">
    function selectId() {
        alert($("select").val());
    }
</script>
}

Result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM