繁体   English   中英

使用JavaScript在ASP.NET MVC中的下拉列表

[英]Dropdown list in asp.net mvc with javascript

我想在“航空公司”标签中显示一个下拉列表。 为此,我在控制器中使用Viewbag将数据加载到下拉列表中。

// 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");
}

和查看为

 @{
        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>

我应该进行哪些更改以获取cshtml和controller方法中的下拉列表。 我正在使用数据库优先方法。 任何人都可以找到我正确的解决方案。 我尝试了很多,但没有成功。

请更改您的Create()GET函数以使其像这样

public ActionResult Create()
{
List<String> AirLinesList = db1.Airlines.ToList();

var selectListItems = AirLinesList.Select(x => new SelectListItem(){ Value = x, Text = x }).ToList();

return View(selectListItems);
}

此外,您应该能够使用DropDownList HTML Helper,它应该使用原始代码就可以接受字符串的集合:

@Html.DropDownList("YourPropertyName", new SelectList(Model))

我的第二个建议实际上是使用您的List集合而不是List来绑定到DropDownList:

@Html.DropDownList("YourPropertyName", new SelectList(Model))

如果要绑定SelectListItems列表,则需要选择适当的属性:

@Html.DropDownList("YourPropertyName", new SelectList(Model, "Value" , "Text"))

默认情况下,将选择列表中的第一项。

这只是示例。 您需要根据需要修改此代码。

步骤1:-为此表创建模型student.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq.Mapping;

namespace MvcApplication1.Models
{
    [Table(Name = "student")]
    public class student
    {
        [Column(IsPrimaryKey = true)]
        public int stu_id { get; set; }
        [Column]
        public string stu_name { get; set; }
        [Column]
        public int stu_age { get; set; }
        [Column]
        public string course { get; set; }
        [Column]
        public int fees { get; set; }

    }
}

步骤2:-添加选择以查看。

<select id="op1"></select>

步骤3:-一次检查您是否正在使用jquery ,然后添加

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

步骤4:-现在控制器需要更改列表数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Linq;
using MvcApplication1.Models;

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {

        public ActionResult Index()
        {

            return View();

        }
        public ActionResult ShowData()
        {
            DataContext dc = new DataContext("connectionstring");
             List<student> lst = dc.GetTable<student>().ToList();
            return Json(lst,JsonRequestBehavior.AllowGet);
        }
    }
}

步骤5:-现在添加您的jquery,以以下方式调用此操作索引:-

 <script>
   $(document).ready(
        function () {
            $(window).load(function () {
                  $.ajax({
                      url: "/home/ShowData",
                    type: "Get",
                    success: function (data) {

                        for (var i = 0; i < data.length; i++) {
                            var opt = new Option(data[i].stu_name, data[i].stu_id);
                            $('#op1').append(opt);
                        }
                    }
                });
            });
    });
</script>

希望它会工作。

在控制器中:

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

在视图中:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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