简体   繁体   中英

Pass javascript value to controller C#

I have created a search function on my website that allows the user to select what table they wnat to search for. The select list is within a dropdown rendered within a dropdown menu using bootstrap. The issue I'm facing is that when the form is run the value of the selected item from the dropdown menu that is passed into the controller is "" instead of the value that was selected in the dropdown menu.

Any help would be grateful.

** search function**

<div class="col-lg-6">
    @{using (Html.BeginForm("Results", "Searchv2", FormMethod.Get))
    {
        <div class="input-group">
            <div class="input-group-btn">
                <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Action <span class="caret"></span></button>
                <ul class="dropdown-menu">
                    @foreach (var searchType in new[] { "User", "Restaurant", "Cuisine" })
                    {
                        <li><a href="">@searchType</a></li>
                    }
                </ul>
                <input type="hidden" name="SearchBy" />
            </div>
            <input type="text" class="form-control" placeholder="Search" name="SearchString" id="SearchString">
        </div>
    }}
</div>

jquery that finds the value

<script>
    $(".dropdown-menu").click(function () {
        $("input[name='SearchBy']").val($(this).html());
    });
</script>

you have to write click event on anchor tag, as you have anchor tag inside <li> like this:

<ul class="dropdown-menu">
 <li>
  <a>SearchText</a>
 </li>
</ul>


$(".dropdown-menu li a").click(function () {


            $("input[name='SearchBy']").val($(this).html());
        });

I believe you want to set the SearchBy value by getting the value of the selected item:

<script>
    $(".dropdown-menu").click(function () {
        $("input[name='SearchBy']").val($(this).val());
    });
</script>

如果要获取<a></a>标记之间的文本值,请尝试使用.text()而不是html()

First you are selecting the ul not the a inside its li and second you should use jquery text function:

<script>
$('.dropdown-menu li a').click(function (e) {
    e.preventDefault();
    $('input[name="SearchBy"]').val($(this).text());
});
</script>

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