Monday, March 14, 2016

Prep .DropDownListFor lists in Razor with default empty first values which a user must explicitly change out.

This is basically the first half of this form revamped a bit:

@model Airport.Core.Objects.Flight
<h1>Add a Flight</h1>
@{
   Dictionary<string,string> dictionary = ViewBag.Cities;
   var cities = new SelectList(dictionary, "Key", "Value");
}
@using (Html.BeginForm("Add", "Flight", FormMethod.Post, new {id="form"}))
{
   <div>
      @Html.LabelFor(m => m.Duration)
      @Html.TextBoxFor(m => m.Duration)
      @Html.ValidationMessageFor(m => m.Duration)
   </div>
   <div>
      @Html.LabelFor(m => m.DepartureTime)
      @Html.TextBox("Date", null, new {@type = "date"})
      @Html.TextBox("Time", null, new {@type = "time"})
      @Html.TextBoxFor(m => m.DepartureTime, new {@class = "displaynone"})
      @Html.ValidationMessageFor(m => m.DepartureTime)
   </div>
   <div>
      @Html.LabelFor(m => m.DepartureCity)
      @Html.DropDownListFor(m => m.DepartureCity, cities)
      @Html.ValidationMessageFor(m => m.DepartureCity)
   </div>
   <div>
      @Html.LabelFor(m => m.DestinationCity)
      @Html.DropDownListFor(m => m.DestinationCity, cities)
      @Html.ValidationMessageFor(m => m.DestinationCity)
   </div>
   <div>
      <input type="submit" value="submit" onclick="var fate = prepare(); return fate;" />
   </div>
}

 
 

The controller...

using System.Collections.Generic;
using System.Web.Mvc;
using Airport.Core.ExternalDependencies;
using Airport.Core.Objects;
namespace Airport.Mvc.Controllers5
{
   public class FlightController : Controller
   {
      private IFlightRepository _flightRepository;
      
      public FlightController(IFlightRepository flightRepository)
      {
         _flightRepository = flightRepository;
      }
      
      public ActionResult Index()
      {
         return View();
      }
      
      public ActionResult Add()
      {
         Dictionary<string, string> cities = new Dictionary<string, string>();
         cities.Add("","");
         foreach (City city in Session["cities"] as List<City>)
         {
            cities.Add(city.CityId.ToString(),city.CityName);
         }
         ViewBag.Cities = cities;
         return View();
      }
      
      [HttpPost]
      public ActionResult Add(Flight flight)
      {
         return View("EndOfAdd");
      }
   }
}

No comments:

Post a Comment