[英]Setting different default values for dropdownlist(MVC5)
I have flights timetable - Schedule view with list of flights Where I just return View and have some filters and sorting. 我有航班时刻表-包含航班清单的时间表视图,我只返回View并进行一些过滤和排序。
Here is part of my view: 这是我观点的一部分:
@model IEnumerable<AirPortIS.Models.Flight>
<div class="page-header">
<h3>Flights</h3>
</div>
<div id="modDialog" class="modal fade">
<div id="dialogContent" class="modal-dialog"></div>
</div>
<table class="table-bordered table-condensed">
<thead>
<tr>
<th>Flight №</th>
<th>Departure</th>
<th>Destination</th>
<th>@Html.ActionLink("Day", "Schedule", new { sort = ViewBag.SortDay, company = ViewBag.FiltrC, destination = ViewBag.FiltrD })</th>
<th>Departure Time</th>
<th>Arrival Time</th>
<th>Company</th>
<th>@Html.ActionLink("Seats", "Schedule", new { sort = ViewBag.SortSeats, company = ViewBag.FiltrC, destination = ViewBag.FiltrD })</th>
<th>@Html.ActionLink("Cost", "Schedule", new { sort = ViewBag.SortCost, company = ViewBag.FiltrC, destination = ViewBag.FiltrD })</th>
<th>Book ticket</th>
</tr>
</thead>
@foreach (var f in Model)
{
<tr>
<td>@Html.ActionLink(f.FlightId.ToString(), "FlightDetails", new { id = f.FlightId }, new {@class = "flItem" } )</td>
<td>@f.Departure</td>
<td>@f.Destination</td>
<td>@f.Day</td>
<td>@f.DepartureTime</td>
<td>@f.ArrivalTime</td>
<td>@f.Company.Name</td>
<td>@f.Seats</td>
<td>@f.Cost</td>
<td>@Html.ActionLink("Link for booking ticket")</td>
</tr>
}
</table>
I need to do that by clicking on a button "Book ticket" user is getting a page where dropdownlist have a preset value of FlightId. 我需要通过单击“书票”按钮来做到这一点,用户将获得一个页面,其中dropdownlist具有FlightId的预设值。 For example we have a flight №1 and a link "Book ticket",so when user goes the booking ticket page he gets a droptdownlist with preselected value "1" 例如,我们有一个№1航班和一个“预订机票”链接,因此,当用户进入预订机票页面时,他会得到一个带有预选值“ 1”的下拉列表。
Here is my ticket Model 这是我的机票模型
public class Tickets
{
public int Id { get; set; }
public int TicketId { get; set; }
public Flight Flight { get; set; }
public string Seat {get;set; }
public string Passenger { get; set; }
public int Flightid { get; set; }
public string Status { get; set; }
}
And part of TicketsController: 以及TicketsController的一部分:
public class TicketsController : Controller
{
private readonly AirportContext _db = new AirportContext();
[Authorize]
public ActionResult Tickets()
{
var ticket = _db.Tickets.Include(t => t.Flight);
return View(ticket);
}
[HttpGet]
public ActionResult BookTicket()
{
IEnumerable<SelectListItem> statusList = new SelectList(new List<string> { "Book", "Buy" });
IEnumerable<SelectListItem> flights = new SelectList(_db.Flights.ToList(), "FlightId", "FlightId");
ViewData["flights"] = flights;
ViewData["statusList"] = statusList;
return View();
}
[HttpPost]
public ActionResult BookTicket(Tickets ticket)
{
IEnumerable<SelectListItem> statusList = new SelectList(new List<string> { "Book", "Buy" });
IEnumerable<SelectListItem> flights = new SelectList(_db.Flights.ToList(), "FlightId", "FlightId");
ViewData["flights"] = flights;
ViewData["statusList"] = statusList;
foreach (var c in _db.Tickets.ToList())
{
if ((_db.Tickets.ToList().Exists(x => c.TicketId == ticket.TicketId)) || (ticket.TicketId <= 0))
{
ModelState.AddModelError("TicketId", "Wrong ticket id");
}
if ((_db.Tickets.ToList().Exists(x => c.Seat == ticket.Seat)) && (_db.Tickets.ToList().Exists(x => c.Flightid == ticket.Flightid))
&& (_db.Tickets.ToList().Exists(x => c.TicketId == ticket.TicketId)))
{
ModelState.AddModelError("Seat", "The seat is unavailable");
}
if (_db.Tickets.ToList().Exists(x => c.Passenger == ticket.Passenger))
{
ModelState.AddModelError("Passenger", "The ticket has already bought");
}
}
if (ModelState.IsValid)
{
_db.Tickets.Add(ticket);
_db.SaveChanges();
return RedirectToAction("Tickets");
}
else return View(ticket);
}
And my BookTikcet View: 而我的BookTikcet视图:
@model AirPortIS.Models.Tickets
@{
ViewBag.Title = "Book ticket";
}
<h2>Book ticket:</h2>
<form class="form-inline" method="post">
<div>
@Html.ValidationSummary()
</div>
<div class="form-group col-md-2">
Ticket №<br/>
@Html.EditorFor(model => Model.TicketId)
</div>
<div class="form-group col-md-1">
Flight №<br />
@Html.DropDownListFor(model => Model.Flightid, ViewData["flights"] as IEnumerable<SelectListItem>)
</div>
<div class="form-group col-md-2">
Место<br />
@Html.EditorFor(model => Model.Seat)
</div>
<div class="form-group col-md-2">
Passenger Name<br />
@Html.EditorFor(model => Model.Passenger)
</div>
<div class="form-group col-md-2">
Status<br />
@Html.DropDownListFor(model => Model.Status, ViewData["statusList"] as IEnumerable<SelectListItem>)
</div>
<div>
<input class="btn-success" type="submit" value="Book Ticket"/>
</div>
</form>
<div>
<form method="get" action="Tickets">
<button class="btn-danger" type="submit">Cancel</button>
</form>
</div>
I have no idea how to do it,so this whole code above just a standart code for creating a new ticket. 我不知道该怎么做,所以上面的整个代码只是用于创建新票证的标准代码。 How I should modify code or add something to have this (For example we have a flight №1 and a link "Book ticket",so when user goes the booking ticket page he gets a droptdownlist with preselected value "1",for flight №2 on a page dropdownlist has a preselected value "2" for FlightId. Hope that my question is clear,sorry if something is wrong written or not quite clear. 我应该如何修改代码或添加一些内容(例如,我们有№1航班和“预订机票”链接,因此,当用户进入预订机票页面时,他会获得一个航班№的下拉列表,其中包含预选值“ 1”页面下拉列表中的2为FlightId预先选择了值“ 2”。希望我的问题很清楚,对不起,如果写错或不清楚。
You need to pass the value of FlightId
as a route (or query string) value to the BookTicket
method. 你需要传递的价值FlightId
作为路径(或查询字符串)值到BookTicket
方法。 You link should be 您的链接应该是
@Html.ActionLink("Book ticket", "BookTicket", new { id = f.FlightId })
and modify the method to 并将方法修改为
[HttpGet]
public ActionResult BookTicket(int ID)
{
... // set you SelectLists as above
// Initialize your model and set the Flightid property
var model = new Tickets()
{
Flightid = ID
};
return View(model); // return the model to the view
}
Your dropdownlist will now have the option identified by Flightid selected when you first generate the view. 现在,您的下拉列表将在您首次生成视图时选择由Flightid标识的选项。
Note. 注意。 I recommend you use a view model rather than your Tickets
data model which will contain properties IEnumerable<SelectListItem> Flights
and IEnumerable<SelectListItem> StatusList
rather than using ViewData
so that your view are strongly typed using 我建议您使用视图模型,而不是Tickets
数据模型,该模型将包含属性IEnumerable<SelectListItem> Flights
和IEnumerable<SelectListItem> StatusList
而不是使用ViewData
以便使用
@Html.DropDownListFor(m => m.Flightid, Model.Flights)
You should also consider refactoring the code to populate the SelectLists
into a private method so that you do not repeat code, for example 您还应该考虑重构代码以将SelectLists
填充到私有方法中,这样就不必重复代码了,例如
private void ConfigureViewModel(TicketVM model)
{
model.Flights = new SelectList(...);
model.StatusList = new SelectList(...);
}
Note also that it is a waste of resources to be calling your database to get the SelectList
's in the POST method if ModelState
is valid. 还请注意,如果ModelState
有效,则在POST方法中调用数据库来获取SelectList
会浪费资源。 Your code should be 您的代码应为
if (!ModelState.IsValid)
{
ConfigureViewModel(model); // only necessary if you need to return the view
return View(model);
}
// save and redirect
Side note: It's unclear why you actually need a dropdownlist for Flightid
in the BookTicket
view. 附注:这是目前还不清楚为什么你确实需要一个下拉列表Flightid
在BookTicket
视图。 The user has already selected the flight so why are you giving the option to change it? 用户已经选择了航班,那么为什么要选择更改航班? It might be more appropriate to just render the Flightid
as a hidden or readonly input so its submitted back to the POST method. 仅将Flightid
呈现为隐藏或只读输入可能更合适,以便将其提交回POST方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.