Search code examples
jqueryrazortextasp.net-mvc-5dropdown

how to pass dropdown selected value from Dropdownlist to a textbox using mvc5 with same view?


I am new to mvc.As a beginner i am trying to pass a dropdown value from a DropdownList to a textbox within same view with a button click. I do some code. but dosen't work. I can populate data on drop sown list but actually submit change event dosen't work. how can I overcome the problem. Here is my image Dropdownlist to textbox

My Dropdown.cshtml View code is here-

@model LoginForm.Models.UserModel

@{
                ViewBag.Title = "Dropdown";
}

<h2>Dropdown List</h2>

<div class="form-horizontal">

</div>

@using (Html.BeginForm("Dropdown", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()


    <div class="form-group" style="padding-top:50px">
        @Html.LabelFor(model => model.UserName, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @(Html.DropDownList("DropdowenList", new SelectList(ViewBag.AllNameList, "CustomerId",
                                                                                "UserName", 0), "Select ...", new { @class = "form-control" }))

        </div>
    </div>


    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Submit" class="btn btn-default" />
            <br />
            <br />
            @Html.TextBox("txtName")

        </div>
    </div>

}

    <script type="text/javascript">
        $(function () {
            $('#DropdowenList').change(function () {
                var selectedValue = $(this).val();
                $('#txtName').val(selectedValue);
            });
        });
    </script>

My HomeCoontroller.Cs code is here-

 [AllowAnonymous]
    public ActionResult Dropdown(string returnUrl)
    {
        ViewBag.Flag = true;
        DropdowncCass dp = new DropdowncCass();
        var allName = dp.GetUserInfo();
        ViewBag.AllNameList = allName;
        Session["allName"] = allName;
        ViewBag.ReturnUrl = returnUrl;
        return View();

    }

Solution

  • You can handle submit button's click event to achieve your goal and use option:selected selector with text() function to set textbox value from dropdown's selected item text:

    $(function () {
         $('.btn').click(function (e) {
             e.preventDefault();
             var selectedValue = $("#DropdowenList option:selected").text();
             $('#txtName').val(selectedValue);
         });
    });
    

    The e.preventDefault() is necessary here because you're using BeginForm helper which renders <form> tag and the function useful to prevent default button submit behavior that posts back the form to controller action.

    This fiddle contains working example that illustrates the desired behavior.