Dropdown list in asp.net mvc with javascript

I want to display a dropdown list in Airline tab. For that I am using Viewbag in controller to load the data in dropdown list.

// GET: /DailyPax/Create
public ActionResult Create()
{

    ViewBag.Airlines = new SelectList(db1.Airlines.ToList(), "Id", "Name");

    return View();
}

// POST: /DailyPax/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for 
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(FormCollection frmcoll, ICollection<string> hddrowpindex)
{
    foreach (var row in hddrowpindex)
    {

        /* 
    CUS_Investment Entry
    */
        DailyPassengerFlow stock = new DailyPassengerFlow();
        stock.FlightNumber = (frmcoll["FlightNumber-" + row]).ToString();
        stock.DepartureDate = DateTime.ParseExact(frmcoll["DepartureDate-" + row], "yyyy/MM/dd", null);
        stock.SectorPair = frmcoll["SectorPair-" + row];
        stock.Airline = frmcoll["Airline-" + row];
        stock.Aircraft = frmcoll["Aircraft-" + row];
        stock.Supply = Convert.ToInt32(frmcoll["Supply-" + row]);
        stock.POB = Convert.ToInt32(frmcoll["POB-" + row]);
        stock.OccPercent = Convert.ToDecimal(frmcoll["OccPercent-" + row]);
        stock.ETD = TimeSpan.Parse(frmcoll["ETD-" + row]);
        stock.ATD = TimeSpan.Parse(frmcoll["ATD-" + row]);
        stock.Delay = TimeSpan.Parse(frmcoll["Delay-" + row]);

        db.DailyPassengerFlows.Add(stock);
        db.SaveChanges();
    }

    return RedirectToAction("Index");
}

and View as

 @{
        ViewBag.Title = "Create";
        Layout = "~/Views/Shared/_Layout.cshtml";
    }

    <div class="col-sm-12">
        <h4> Daily Passenger Entry</h4>
    </div>
    <script>

    </script>

    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()


        <div id="PrimaryPurchase" style="display:inline" class="col-sm-12">
            <table class="table table-bordered table-striped dataTable" id="portfolio">
                <thead>
                    <tr>

                        <th class="" style="width:8%">Flight No.</th>
                        <th class="" style="width:10%">Date</th>
                        <th class="" style="width:8%">Sector</th>
                        <th class="" style="width:14%">Airline</th>
                        <th class="" style="width:8%">Aircraft</th>
                        <th class="" style="width:8%">Supply</th>
                        <th class="" style="width:8%">POB</th>
                        <th class="" style="width:8%">Occ %</th>
                        <th class="" style="width:7%">ETD</th>

                        <th class="" style="width:7%">ATD</th>
                        <th class="" style="width:7%">Delay</th>
                        <th class="" style="width:5%"></th>
                    </tr>
                </thead>
                <tbody>

                    @*<div id="itemList">


                        </div>*@
                </tbody>
            </table>

            <div class="form-group col-sm-12"><span onclick="addItem()" style="cursor:pointer;width:80px;" class="btn btn-primary"><i class="fa fa-plus" style="padding-right:5px;"></i>Add</span></div>

        </div>
        <div class="form-group col-sm-12"><input type="submit" value="Save" class="btn btn-primary" style="width:80px;" /></div>

    }

    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    <style>
        td {
            padding: 0 !important;
        }
    </style>
    <script>
        var cd = new Date();
        var rowindex = 1;
        function addItem() {

            msg = '<tr><input type="hidden" name="hddrowpindex" value="' + rowindex + '" class="rowcount"/>';

            msg += '<td class="center-fix" >';
            msg += '<input class="form-control" style="text-transform:uppercase; padding:0px,margin:0px;" type="text" name="FlightNumber-' + rowindex + '" id="FlightNumber-' + rowindex + '" placeholder="YA-000" />';
            msg += '</td>';
            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control datepicker" name="DepartureDate-' + rowindex + '" id="DepartureDate-' + rowindex + '" placeholder="YYYY/MM/DD" />';
            msg += '</td>';
            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control" style="text-transform:uppercase" name="SectorPair-' + rowindex + '" id="SectorPair-' + rowindex + '" placeholder="SOU-DES" />';
            msg += '</td>';
            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control" style="text-transform:uppercase" name="Airline-' + rowindex + '" id="Airline-' + rowindex + '" placeholder="Airline" />';
            msg += '</td>';
            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control" style="text-transform:uppercase" name="Aircraft-' + rowindex + '" id="Aircraft-' + rowindex + '" placeholder="Aircraft"  />';
            msg += '</td>';
            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control" name="Supply-' + rowindex + '" id="Supply-' + rowindex + '" placeholder="Supply" value="0" onblur="calcpercent(' + rowindex + ')" />';
            msg += '</td>';

            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control"  name="POB-' + rowindex + '" id="POB-' + rowindex + '" placeholder="0" value="0" onblur="calcpercent(' + rowindex + ')" />';
            msg += '</td>';
            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control" name="OccPercent-' + rowindex + '" id="OccPercent-' + rowindex + '" placeholder="0" value="0" />';
            msg += '</td>';
            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control " name="ETD-' + rowindex + '" id="ETD-' + rowindex + '" placeholder="hh:mm"  value="00:00" onblur="calcdelay(' + rowindex + ')"  />';
            msg += '</td>';

            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control"  name="ATD-' + rowindex + '" id="ATD-' + rowindex + '" placeholder="hh:mm" value="00:00" onblur="calcdelay(' + rowindex + ')" />';
            msg += '</td>';
            msg += '<td class="center-fix">';
            msg += '<input type="text" class="form-control" name="Delay-' + rowindex + '" id="Delay-' + rowindex + '" placeholder="hh:mm" value="00:00" />';
            msg += '</td>';
            msg += '<td class="center-fix" style="text-align:center;"><a href="" ><span id="remove-' + rowindex + '"  style="cursor:pointer"><i class="fa fa-trash"></i>Remove</span></a>';
            msg += '&nbsp;<span id="perror-' + rowindex + '" style="display:none"><i class="fa fa-exclamation-triangle faa-exclamation-triangle animated"></i></span></td>';
            msg += '</tr>';


            $('table#portfolio tbody').append(msg);
            $(".datepicker").datepicker({
                defaultDate: cd,
                changeMonth: true,
                changeYear: true,
                yearRange: '2015:2030',
                dateFormat: 'yy/mm/dd'
            });

            rowindex++;
        }

    </script>
    @*<script src="https://www.aber.ac.uk/corporate-javascript/jquery/jquery-1.6.2.js"></script>*@
    @*<script src="~/assets/js/ajax/libs/jquery/1.10.1/jquery.min.js"></script>*@
    <script>

        $(function () {
            debugger;
            $("#portfolio").on("click", "tr a", function (e) {
                e.preventDefault();
                if (confirm("Are you sure to remove?")) {
                    //removeitem($(this).closest("tr").find(".rowcount").val());
                    $(this).parents('tr').remove();
                    //computeAvg();
                }
            });
        });

        function calcpercent(rowind) {
            $("#OccPercent-" + rowind).val(Math.round(($("#POB-" + rowind).val() / $('#Supply-' + rowind).val()) * 100));
        }

        function calcdelay(rowinde) {
            var etd = ($("#ETD-" + rowinde).val()).split(':');
            var atd = ($("#ATD-" + rowinde).val()).split(':');
            var etds = etd[0] * 60 * 60 + etd[1] * 60;
            var atds = atd[0] * 60 * 60 + atd[1] * 60;
            var delay = atds - etds;
            if (delay < 0) {
                delay = delay * -1;
            }
            d = Number(delay);
            var h = Math.floor(d / 3600);
            var m = Math.floor(d % 3600 / 60);
            if (h < 10) {
                h = "0" + h;
            }
            if (m < 10) {
                m = "0" + m;
            }
            $("#Delay-" + rowinde).val(h + ":" + m);
        }

    </script>

What changes should i make to get the dropdown list in the cshtml and controller method. I am using database first approach method. Anyone please find me the right solutions. I tried a lot but can't get.

Answers 1

  • In Controller:

    ViewBag.Airlines = new SelectList(db1.Airlines,"Id","Name");
    

    In View:

    @Html.DropDownList("list", ViewBag.Airlines as SelectList, "Id","Name")
    

Related Articles