Search code examples
javascriptmodel-view-controllerdropdownviewbag

how to save my dropdown selected values to a textbox...using javascript?


Controller

public ActionResult ItemInsert()
        {
            ViewBag.Category = new SelectList(db.CategoryMasters.ToList(), "CategoryId", "CategoryName");
            ItemViewModel item = new ItemViewModel();
            return PartialView(item);
        }

View

<div class="form-group">
            @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                    @Html.DropDownList("Category", ViewBag.Category as SelectList, new { @id = "catagory" })
                    @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
            </div>
        </div>

how to save dropdown values using javascript?


Solution

  • View

    <div class="form-group">
                @Html.LabelFor(model => model.CategoryId, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                   <div hidden>@Html.EditorFor(model => model.CategoryId, new { htmlAttributes = new { @class = "form-control", id = "categoryid" } })</div>
                        @Html.DropDownList("any value", ViewBag.category as SelectList,"--SELECT--", new { @id = "category" })
                        @Html.ValidationMessageFor(model => model.CategoryId, "", new { @class = "text-danger" })
                </div>
            </div>
    

    JS

    <script type="text/javascript">
        $(document).ready(function () {
            $("#category").change(function () {
                var value = $(this).val();
                alert(+value)
                $("#categoryid").val(value);
            });
        });
    </script>