Here is my problem , So i wanted to only allowing the user to change/edit their password and username only.
My original model for customer is this
public string IC { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Username{ get; set; }
public string Password{ get; set; }
And this is my VM for the customer
public string Username{ get; set; }
public string Password{ get; set; }
And this is my controller for the edit function
public ActionResult Edit([Bind(Include = "Username,Password")] CustomersVM customersVM )
{
if (ModelState.IsValid)
{
db.Entry(customersVM ).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customersVM );
}
view.cshtml
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.IC)
<div class="form-group">
#Html.LabelFor(model => model.Username, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Username, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Username, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Password, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Password, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
</div>
So this VM is to let the ModelState goes valid, which is will going right into the database but it turn out to turn this type of error
System.InvalidOperationException: 'The entity type CustomerVM is not part of the model for the current context.'
In order to edit/update a record, you need to identify that record first. I your case, your ViewModel is not what your database holds but the first model in your question. So you need to map that viewModel to the real model before saving or fetch the existing record then modify it then set it as modified before saving.
public ActionResult Edit([Bind(Include = "Username,Password")] CustomersVM customersVM )
{
if (ModelState.IsValid)
{
var existing = db.Customers.FirstOrDefault(x => x.Id == customersVM.Id);
if (existing != null)
{
existing.Username = customersVM.Username;
existing.Password = customerVM.Password;
db.Entry(existing ).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(customersVM );
}
Not sure where the issue is - the file upload is working fine and going to the correct folder however the path and filename are not being stored in the database.
I want to use this so that I can add links to my index view for each document uploaded.
Any help on this would be brilliant as I have been racking my brains for 2 days over this.
Regards
Andy
Model:
namespace inventIT.Models
{
using System;
using System.Collections.Generic;
public partial class ComputerInventory
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ComputerInventory()
{
this.ComputerInstallations = new HashSet<ComputerInstallation>();
}
public int RecordID { get; set; }
public string ComputerAdName { get; set; }
public string ComputerBrand { get; set; }
public string ComputerModel { get; set; }
public string ComputerSerialNumber { get; set; }
public string ComputerOS { get; set; }
public System.DateTime ComputerPurchaseDate { get; set; }
public string ComputerAddedBy { get; set; }
public Nullable<bool> ComputerArchived { get; set; }
public Nullable<System.DateTime> ComputerArchivedDate { get; set; }
public string FileDesc { get; set; }
public string FileName { get; set; }
public string Extension { get; set; }
public Nullable<int> FileID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ComputerInstallation> ComputerInstallations { get; set; }
public virtual Lookup Lookup { get; set; }
public virtual Lookup Lookup1 { get; set; }
public virtual ITTeamLookup ITTeamLookup { get; set; }
public virtual Lookup Lookup2 { get; set; }
}
}
Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using inventIT.Models;
namespace inventIT.Controllers
{
public class ComputerInventoriesController : Controller
{
private HAWKTRAINING_INVENTITEntities db = new HAWKTRAINING_INVENTITEntities();
// GET: ComputerInventories
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? PageSize)
{
ViewBag.searchString = "";
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var AssessorIDs = from s in db.ComputerInventories
select s;
if (!String.IsNullOrEmpty(searchString))
{
AssessorIDs = AssessorIDs.Where(s => s.ComputerAdName.Contains(searchString) || searchString == null || searchString == "");
}
switch (sortOrder)
{
case "name_desc":
AssessorIDs = AssessorIDs.OrderByDescending(s => s.ComputerAdName);
break;
case "Date":
AssessorIDs = AssessorIDs.OrderBy(s => s.ComputerPurchaseDate);
break;
case "date_desc":
AssessorIDs = AssessorIDs.OrderByDescending(s => s.ComputerPurchaseDate);
break;
default: // Name ascending
AssessorIDs = AssessorIDs.OrderBy(s => s.ComputerAdName);
break;
}
var computerInventories = db.ComputerInventories.Include(c => c.Lookup).Include(c => c.Lookup1).Include(c => c.ITTeamLookup).Include(c => c.Lookup2);
return View(computerInventories.Where(s => s.ComputerAdName.Contains(searchString) || searchString == null || searchString == "").OrderByDescending(c => c.ComputerAdName).ToList());
}
// GET: ComputerInventories/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
return View(computerInventory);
}
// GET: ComputerInventories/Create
public ActionResult Create()
{
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View();
}
// POST: ComputerInventories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RecordID,ComputerAdName,ComputerBrand,ComputerModel,ComputerSerialNumber,ComputerOS,ComputerPurchaseDate,ComputerAddedBy,ComputerArchived,ComputerArchivedDate,FileDesc,FileName,Extension,FileID")] ComputerInventory computerInventory)
{
if (ModelState.IsValid)
{
List<ComputerInventory> fileDetails = new List<ComputerInventory>();
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
ComputerInventory fileDetail = new ComputerInventory()
{
FileName = fileName,
Extension = Path.GetExtension(fileName),
FileID = computerInventory.RecordID
};
fileDetails.Add(fileDetail);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/"), fileDetail.FileName);
file.SaveAs(path);
}
}
computerInventory.FileID = computerInventory.FileID;
computerInventory.Extension = computerInventory.Extension;
computerInventory.FileDesc = computerInventory.FileDesc;
computerInventory.FileName = computerInventory.FileName;
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
if (ModelState.IsValid)
{
try
{
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
return View("Error", new HandleErrorInfo(ex, "ComputerInventories", "Create"));
}
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
[HttpPost]
[ValidateAntiForgeryToken]
// GET: ComputerInventories/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
// POST: ComputerInventories/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "RecordID,ComputerAdName,ComputerBrand,ComputerModel,ComputerSerialNumber,ComputerOS,ComputerPurchaseDate,ComputerAddedBy,ComputerArchived,ComputerArchivedDate,FileDesc,FileName,Extension,FileID")] ComputerInventory computerInventory)
{
if (ModelState.IsValid)
{
db.Entry(computerInventory).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
// GET: ComputerInventories/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
return View(computerInventory);
}
// POST: ComputerInventories/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
db.ComputerInventories.Remove(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
View
#model inventIT.Models.ComputerInventory
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Computer Assets</h2>
#using (Html.BeginForm("Create", "ComputerInventories", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ComputerAdName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerAdName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ComputerAdName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerBrand, "ComputerBrand", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerBrand", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerBrand, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerModel, "ComputerModel", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerModel", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerModel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerSerialNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerSerialNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ComputerSerialNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerOS, "ComputerOS", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerOS", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerOS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerPurchaseDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerPurchaseDate, new { htmlAttributes = new { #class = "form-control jqueryui-marker-datepicker" } })
#Html.ValidationMessageFor(model => model.ComputerPurchaseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerAddedBy, "ComputerAddedBy", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerAddedBy", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerAddedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerArchived, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.ComputerArchived)
#Html.ValidationMessageFor(model => model.ComputerArchived, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerArchivedDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerArchivedDate, new { htmlAttributes = new { #class = "form-control jqueryui-marker-datepicker" } })
#Html.ValidationMessageFor(model => model.ComputerArchivedDate, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(x => x.FileDesc)
<input type="file" name="file" id="file" />
<input type="submit" value="submit" />
You seems to be missing Path property in your ComputerInventory and hence in your table too. you are not setting your path to any property . How do you expect it to be saved in database?
First add a column in Table as FilePath, update Model ComputerInventory and set path to this FilePath variable
Class ComputerInventory()
{
public string FilePath { get; set; }
//other properties;
}
computerInventory.FilePath = path;
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();
I want to show all names of "Category" in the dropdownlist in Create View by HtmlHelper.
The Model of "Category" is:
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
The Controller is:
public ActionResult Create()//
{
ViewBag.Categorys = new SelectList(categoryRepo.SelectAll(), "Id", "Name");
return View();
}
The View is:
<div class="form-group">
#Html.LabelFor(model => model.CategoryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CategoryId, (SelectList)ViewBag.Categorys, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CategoryId, "", new { #class = "text-danger" })
</div>
</div>
You may try this,
#Html.DropDownList("Categorys", null, "Select Category", new {#class="form-control"})
I am currently new to Asp.net MVC .In one of the view I add a dropdownlist and I bind this dropdownlist with my database like this
Controller CollegeController
[HttpGet]
public ActionResult Create()
{
IEnumerable<SelectListItem> items = db.College_Names.Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.Name });
IEnumerable<SelectListItem> item = db.Stream_Names.Select(c => new SelectListItem { Value = c.id.ToString(), Text = c.Stream });
ViewBag.CollName=items;
ViewBag.StreamName = item;
return View();
}
[HttpPost]
public ActionResult Create(College college)
{
try
{
if(ModelState.IsValid)
{
db.Colleges.Add(college);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CollName = db.Colleges;
return View(college);
}
catch
{
return View();
}
}
This is my model
public class College
{
[Required]
public int Id { get; set; }
[Required]
[Display(Name="College Name")]
public int CollegeName { get; set; }
[Required]
public int Stream { get; set; }
[Required]
[Column(TypeName="varchar")]
public string Name { get; set; }
....
public virtual College_Name College_Name { get; set; }
public virtual Stream_Name Stream_Name { get; set; }
}
This is My View
<div class="form-group">
#Html.LabelFor(model => model.CollegeName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CollName", (IEnumerable<SelectListItem>)ViewBag.CollName, "Select College", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CollegeName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Stream, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StreamName", (IEnumerable<SelectListItem>)ViewBag.StreamName, "Select Stream", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Stream, "", new { #class = "text-danger" })
</div>
</div>
Now when I check my database after I save the CollegeName and Stream in the database is zero from the dropdownlist.
You have multiple problems with your code. Firstly you dropdownlists are binding to a properties named CollName and StreamName which do not even exist in your model.
Next you cannot name the property your binding to the same as the ViewBag property.
Your view code would need to be (and always use the strongly typed xxxFor() HtmHelper methods
#Html.DropDownListFor(m => m.CollegeName, (IEnumerable<SelectListItem>)ViewBag.CollName, "Select College", new { #class = "form-control" })
....
#Html.DropDownListFor(m => m.Stream, (IEnumerable<SelectListItem>)ViewBag.StreamName, "Select Stream", new { #class = "form-control" }
and in your POST method, the values of college.CollegeName and college.Stream will contain the ID's of the selected options.
You also need to repopulate the ViewBag properties when you return the view in the POST method (as you did in the GET method) or an exception will be thrown (and note that your current use of ViewBag.CollName = db.Colleges; will also throw an exception)
I also strongly suggest you start learning to use view models (views for editing should not use data models - refer What is ViewModel in MVC?) - and use naming conventions that reflect what your properties are, for example CollegeNameList, or CollegeNames, not CollName
I have been looking for a while now and can't seem to find the answer. What I am trying to do is have the current date and the current Time in two fields on a create page. This page will be used for basic journey scheduling.
What I have so far is my model
public class Journey
{
public int JourneyId { get; set; }
public string Name { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}",ApplyFormatInEditMode = true)]
public DateTime Departure { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(DataFormatString="{0:hh\\:mm}", ApplyFormatInEditMode = true)]
public TimeSpan DepartureTime { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Arrival { get; set; }
public string Description { get; set; }
public int FareId { get; set; }
public int TrainId { get; set; }
public virtual FareType FareType { get; set; }
public virtual Train Train { get; set; }
}
Account Controller
public class JourneyController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
//
// GET: Journey
public ActionResult Index()
{
return View(db.Journey.ToList());
}
//
// GET: Journey/Create
public ActionResult Create()
{
ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name");
return View();
}
// POST: Journey/Create
[HttpPost]
public ActionResult Create(Journey model)
{
try
{
if (ModelState.IsValid)
{
db.Journey.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name", model.TrainId);
return RedirectToAction("Index");
}
catch (DataException)
{
ModelState.AddModelError("", "Sorry something went wrong");
}
return View(model);
}
}
And finaly my view
<div class="form-horizontal">
<h4>Journey</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Departure, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Departure, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Departure, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DepartureTime., new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DepartureTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Arrival, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Arrival, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Arrival, "", new { #class = "text-danger" })
</div>
</div>
Any help would be great
Many thanks
Use custom getters and setters on your DateTime property to provide a default of now:
private DateTime? departure;
public DateTime Departure
{
get { return departure ?? DateTime.Today; }
set { departure = value; }
}
private DateTime? departureTime;
public DateTime DepartureTime
{
get { return departureTime ?? DateTime.Now; }
set { departureTime = value; }
}
private DateTime? arrival;
public DateTime Arrival
{
get { return arrival ?? DateTime.Today; }
set { arrival = value; }
}
Alternatively, you can just manually set the values in your action:
public ActionResult Create()
{
var journey = new Journey
{
Departure = DateTime.Today,
DepartureTime = DateTime.Now,
Arrival = DateTime.Today
};
ViewBag.TrainId = new SelectList(db.Train, "TrainId", "Name");
return View(journey);
}