[英]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 += ' <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.