Uploading files from MVC Edit Page/View - c#

I have a very basic mvc project with the standard Edit view & I am trying to add the option to upload a file directly from that view.
I have successfully implemented the upload option from the Create view but it does not work from the Edit view for some reason.
Edit view (file upload and save)
<div class="form-group">
#Html.Label("Attach File", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="file" name="upload" />
</div>
</div>
<div>
<input type="submit" value="Save" class="btn btn-default" />
</div>
Edit Controller
// POST: Travel/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 = "TravelID,RequestedBy,DateRequested,TravelDescription,DestinationCity,DestinationState,StartDate,EndDate,EstRegistrationPerPerson,EstAirfarePerPerson,EstGroundPerPerson,EstLodgingPerPerson,EstMealsPerPerson,DepartureCity,DepartureState,DepartureDate,DepartureTimeRange,ReturnFromCity,ReturnFromState,ReturnFromDate,ReturnFromTimeRange,FlightNote,Hotel,HotelPhone,HotelNote,NeedHotelArrangements,NeedFlightArrangements,NeedRentalCarArrangements,IsTripInTravelBudget,Justification,OtherNote,SupAuth,SupAuthDate,CEOAuth,CEOAuthDate,ActRegistrationPerPerson,ActAirfarePerPerson,ActGroundPerPerson,ActLodgingPerPerson,ActMealsPerPerson")] Travel travel, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
var file = new Files
{
TravelID = travel.TravelID,
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
file.Content = reader.ReadBytes(upload.ContentLength);
}
travel.Files = new List<Files> { file };
}
db.Entry(travel).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", "Travel", new { id = travel.TravelID });
}
return View(travel);
}
When I submit the edits, all additional fields update as expected BUT no file is uploaded.
Files Model:
namespace TrainingAndTravel.Models
{
using System;
using System.Collections.Generic;
public partial class Files
{
public int FileID { get; set; }
public int TravelID { get; set; }
public string FileName { get; set; }
public string FileType { get; set; }
public byte[] Content { get; set; }
public virtual Travel Travel { get; set; }
}
}
Travel Model:
namespace TrainingAndTravel.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Travel
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Travel()
{
this.Files = new HashSet<Files>();
this.Travelers = new HashSet<Travelers>();
}
[Display(Name = "Travel ID")]
public int TravelID { get; set; }
[Display(Name = "Requested By")]
public string RequestedBy { get; set; }
[Display(Name = "Date Requested")]
[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public System.DateTime DateRequested { get; set; }
[Display(Name = "Travel Description")]
public string TravelDescription { get; set; }
[Display(Name = "Destination City")]
public string DestinationCity { get; set; }
[Display(Name = "Destination State")]
public string DestinationState { get; set; }
[Display(Name = "Start Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> StartDate { get; set; }
[Display(Name = "End Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> EndDate { get; set; }
[Display(Name = "Estimated Registration Per Person")]
public Nullable<decimal> EstRegistrationPerPerson { get; set; }
[Display(Name = "Estimated Airfare Per Person")]
public Nullable<decimal> EstAirfarePerPerson { get; set; }
[Display(Name = "Estimated Ground Per Person")]
public Nullable<decimal> EstGroundPerPerson { get; set; }
[Display(Name = "Estimated Lodging Per Person")]
public Nullable<decimal> EstLodgingPerPerson { get; set; }
[Display(Name = "Estimated Meals Per Person")]
public Nullable<decimal> EstMealsPerPerson { get; set; }
[Display(Name = "Departure City")]
public string DepartureCity { get; set; }
[Display(Name = "Departure State")]
public string DepartureState { get; set; }
[Display(Name = "Departure Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DepartureDate { get; set; }
[Display(Name = "Departure Time Range")]
public string DepartureTimeRange { get; set; }
[Display(Name = "Return From City")]
public string ReturnFromCity { get; set; }
[Display(Name = "Return From State")]
public string ReturnFromState { get; set; }
[Display(Name = "Return From Date")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> ReturnFromDate { get; set; }
[Display(Name = "Return From Time Range")]
public string ReturnFromTimeRange { get; set; }
[Display(Name = "Flight Note")]
public string FlightNote { get; set; }
public string Hotel { get; set; }
[Display(Name = "Hotel Phone")]
public string HotelPhone { get; set; }
[Display(Name = "Hotel Note")]
public string HotelNote { get; set; }
[Display(Name = "Need Hotel Arrangements")]
public bool NeedHotelArrangements { get; set; }
[Display(Name = "Need Flight Arrangements")]
public bool NeedFlightArrangements { get; set; }
[Display(Name = "Need Rental Car Arrangements")]
public bool NeedRentalCarArrangements { get; set; }
[Display(Name = "Is Trip In Travel Budget")]
public bool IsTripInTravelBudget { get; set; }
public string Justification { get; set; }
[Display(Name = "Other Note")]
public string OtherNote { get; set; }
[Display(Name = "Supervisor Authorization")]
public string SupAuth { get; set; }
[Display(Name = "Supervisor Authorization Date & Time")]
[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> SupAuthDate { get; set; }
[Display(Name = "CEO Authorization")]
public string CEOAuth { get; set; }
[Display(Name = "CEO Authorization Date & Time")]
[DisplayFormat(DataFormatString = "{0:g}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> CEOAuthDate { get; set; }
[Display(Name = "Actual Registration Per Person")]
public Nullable<decimal> ActRegistrationPerPerson { get; set; }
[Display(Name = "Actual Airfare Per Person")]
public Nullable<decimal> ActAirfarePerPerson { get; set; }
[Display(Name = "Actual Ground Per Person")]
public Nullable<decimal> ActGroundPerPerson { get; set; }
[Display(Name = "Actual Lodging Per Person")]
public Nullable<decimal> ActLodgingPerPerson { get; set; }
[Display(Name = "Actual Meals Per Person")]
public Nullable<decimal> ActMealsPerPerson { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Files> Files { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Travelers> Travelers { get; set; }
}
}
Entire Edit View:
#model TrainingAndTravel.Models.Travel
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Edit Travel Request</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.TravelID)
<div hidden class="form-group">
#Html.LabelFor(model => model.RequestedBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RequestedBy, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.RequestedBy, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.DateRequested, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DateRequested, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.DateRequested, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TravelDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TravelDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TravelDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DestinationCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DestinationCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DestinationCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DestinationState, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DestinationState, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DestinationState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstRegistrationPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstRegistrationPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstRegistrationPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstAirfarePerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstAirfarePerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstAirfarePerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstGroundPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstGroundPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstGroundPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstLodgingPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstLodgingPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstLodgingPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EstMealsPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EstMealsPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EstMealsPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DepartureCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DepartureCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureState, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DepartureState, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DepartureState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DepartureDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DepartureDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DepartureTimeRange, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.DepartureTimeRange, TrainingAndTravel.Utils.TimeRangeList.GetTimeRangeList(), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.DepartureTimeRange, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReturnFromCity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnFromCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReturnFromCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReturnFromState, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnFromState, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReturnFromState, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReturnFromDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReturnFromDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReturnFromDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReturnFromTimeRange, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ReturnFromTimeRange, TrainingAndTravel.Utils.TimeRangeList.GetTimeRangeList(), new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ReturnFromTimeRange, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FlightNote, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FlightNote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FlightNote, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Hotel, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Hotel, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Hotel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HotelPhone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HotelPhone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HotelPhone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HotelNote, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HotelNote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HotelNote, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Justification, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Justification, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Justification, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OtherNote, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OtherNote, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OtherNote, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NeedHotelArrangements, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.NeedHotelArrangements, new { #class = "checkbox" })
#Html.ValidationMessageFor(model => model.NeedHotelArrangements, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NeedFlightArrangements, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.NeedFlightArrangements, new { #class = "checkbox" })
#Html.ValidationMessageFor(model => model.NeedFlightArrangements, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NeedRentalCarArrangements, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.NeedRentalCarArrangements, new { #class = "checkbox" })
#Html.ValidationMessageFor(model => model.NeedRentalCarArrangements, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsTripInTravelBudget, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.IsTripInTravelBudget, new { #class = "checkbox" })
#Html.ValidationMessageFor(model => model.IsTripInTravelBudget, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActRegistrationPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActRegistrationPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActRegistrationPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActAirfarePerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActAirfarePerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActAirfarePerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActGroundPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActGroundPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActGroundPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActLodgingPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActLodgingPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActLodgingPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div hidden class="form-group">
#Html.LabelFor(model => model.ActMealsPerPerson, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ActMealsPerPerson, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActMealsPerPerson, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Attach File", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="file" name="upload" />
</div>
</div>
<div>
<input type="submit" value="Save" class="btn btn-default" />
#Html.ActionLink("Cancel", "Details", "Travel", new { id = Model.TravelID }, new { #class = "btn btn-default" })
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}

You need to add enctype attribute in form tag on view
View
<form action="" method="post" enctype="multipart/form-data">
<!-- your remaing code-->
<div class="form-group">
#Html.Label("Attach File", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="file" name="upload" />
</div>
</div>
<input type="submit" />
</form>
More Info check here

I had to rearrange my controller a bit, placing the upload portion below the EntityState.Modified and SaveChanges, also needed a db.SaveChanges() below the upload:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "TravelID,RequestedBy,DateRequested,TravelDescription,DestinationCity,DestinationState,StartDate,EndDate,EstRegistrationPerPerson,EstAirfarePerPerson,EstGroundPerPerson,EstLodgingPerPerson,EstMealsPerPerson,DepartureCity,DepartureState,DepartureDate,DepartureTimeRange,ReturnFromCity,ReturnFromState,ReturnFromDate,ReturnFromTimeRange,FlightNote,Hotel,HotelPhone,HotelNote,NeedHotelArrangements,NeedFlightArrangements,NeedRentalCarArrangements,IsTripInTravelBudget,Justification,OtherNote,SupAuth,SupAuthDate,CEOAuth,CEOAuthDate,ActRegistrationPerPerson,ActAirfarePerPerson,ActGroundPerPerson,ActLodgingPerPerson,ActMealsPerPerson")] Travel travel, HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
db.Entry(travel).State = EntityState.Modified;
db.SaveChanges();
if (upload != null && upload.ContentLength > 0)
{
var file = new Files
{
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
file.Content = reader.ReadBytes(upload.ContentLength);
}
travel.Files = new List<Files> { file };
}
db.SaveChanges();
return RedirectToAction("Details", "Travel", new { id = travel.TravelID });
}
return View(travel);
}

Related

asp.net MVC upload file name is System.Web.HttpPostedFileWrapper

AdminBlog is my controllers name.
Blog is a table in my database.
Foto is a column in the table.
when i saved the form, Foto column value become System.Web.HttpPostedFileWrapper. But others column's values are getting correct values. Also the image does not upload to BlogFoto file
Here is my model codes:
public partial class Blog
{
public int BlogID { get; set; }
public string BlogBaslik { get; set; }
[UIHint("tinymce_full")][AllowHtml]
public string BlogIcerik { get; set; }
public string Foto { get; set; }
public Nullable<int> BlogOkunmaSayisi { get; set; }
public Nullable<int> BlogOkunmaSuresi { get; set; }
public Nullable<System.DateTime> BlogTarih { get; set; }
}
and view codes:
#using (Html.BeginForm("Create", "AdminBlog",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Yeni Blog Oluştur</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.BlogBaslik, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BlogBaslik, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BlogBaslik, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BlogIcerik, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BlogIcerik, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BlogIcerik, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Foto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="Foto" class="form-control" />
#Html.ValidationMessageFor(model => model.Foto, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BlogOkunmaSuresi, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BlogOkunmaSuresi, new { htmlAttributes = new { #class = "form-control", #placeholder = "DK cinsinden giriniz" } })
#Html.ValidationMessageFor(model => model.BlogOkunmaSuresi, "", new { #class = "text-danger" })
</div>
</div>
and controllers:
[HttpPost]
public ActionResult Create(Blog blog, HttpPostedFile Foto)
{
try
{
if (Foto != null)
{
WebImage webImage = new WebImage(Foto.InputStream);
string newfoto = Path.GetFileNameWithoutExtension(Foto.FileName) + "-" + Guid.NewGuid() + Path.GetExtension(Foto.FileName);
var filePath = "/Uploads/BlogFoto" + newfoto;
webImage.Save(Server.MapPath(filePath));
blog.Foto = filePath;
}
blog.BlogOkunmaSayisi = 0;
blog.BlogTarih = DateTime.Now;
db.Blogs.Add(blog);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
change Blog to this :
public partial class Blog
{
//...............................
//...............................
public HttpPostedFileBase FotoFile { get; set; }
}
this code
<div class="form-group">
#Html.LabelFor(model => model.Foto, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="Foto" class="form-control" />
#Html.ValidationMessageFor(model => model.Foto, "", new { #class = "text-danger" })
</div>
</div>
change to this :
<div class="form-group">
#Html.LabelFor(model => model.FotoFile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.FotoFile, new { type = "file", #class = "form-control" })
#Html.ValidationMessageFor(model => model.FotoFile, null, new { #class = "text-danger" })
</div>
</div>
and change controllert to this :
[HttpPost]
public ActionResult Create(Blog blog)
{
try
{
if (blog.FotoFile != null)
{
WebImage webImage = new WebImage(blog.FotoFile.InputStream);
string newfoto = Path.GetFileNameWithoutExtension(blog.FotoFile.FileName) + "-" + Guid.NewGuid() + Path.GetExtension(blog.FotoFile.FileName);
var filePath = "/Uploads/BlogFoto" + newfoto;
webImage.Save(Server.MapPath(filePath));
blog.Foto = filePath;
}
//..................................................................
//..................................................................
}
catch
{
return View();
}
}

C# ASP.NET RAZOR : double validation

Please help : the validator does not validate a double value:
When I type a Double value with a dot or a vergule the validator displays me an error message that the value is not valid:
when I type a value with vergule he gives me this message:
The LONGITUDE field must be a number.
while when I type a value with point he gives me this message:
The value "230.5" is not valid for ATTITUDE.
this is the code of the view:
#model Miam.Models.diverse_info_commerce
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>diverse_info_commerce</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ID_COMMERCE, "ID_COMMERCE", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ID_COMMERCE", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ID_COMMERCE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.VILLE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.VILLE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.VILLE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.RUE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.RUE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.RUE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NUMERO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.NUMERO, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NUMERO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LONGITUDE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LONGITUDE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LONGITUDE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ATTITUDE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ATTITUDE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ATTITUDE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PAYS, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PAYS, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PAYS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HEUR_OUVERTURE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HEUR_OUVERTURE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HEUR_OUVERTURE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HEUR_FERMETURE, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HEUR_FERMETURE, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HEUR_FERMETURE, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" hidden>
#Html.LabelFor(model => model.CREATED_AT, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CREATED_AT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CREATED_AT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group" hidden>
#Html.LabelFor(model => model.UPDATED_AT, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UPDATED_AT, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UPDATED_AT, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
The model:
namespace Miam.Models
{
using System;
using System.Collections.Generic;
public partial class diverse_info_commerce
{
public int ID_POSITION { get; set; }
public Nullable<int> ID_COMMERCE { get; set; }
public string VILLE { get; set; }
public string RUE { get; set; }
public int NUMERO { get; set; }
public double LONGITUDE { get; set; }
public double ATTITUDE { get; set; }
public string PAYS { get; set; }
public System.DateTime HEUR_OUVERTURE { get; set; }
public System.DateTime HEUR_FERMETURE { get; set; }
public System.DateTime CREATED_AT { get; set; }
public System.DateTime UPDATED_AT { get; set; }
public virtual commerce commerce { get; set; }
}
}
The controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "ID_POSITION,ID_COMMERCE,VILLE,RUE,NUMERO,LONGITUDE,ATTITUDE,PAYS,HEUR_OUVERTURE,HEUR_FERMETURE")] diverse_info_commerce diverse_info_commerce)
{
if (ModelState.IsValid)
{
diverse_info_commerce.UPDATED_AT = DateTime.Now;
diverse_info_commerce.CREATED_AT= DateTime.Now;
db.diverse_info_commerce.Add(diverse_info_commerce);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.ID_COMMERCE = new SelectList(db.commerces, "ID_COMMERCE", "TITRE_COMMERCE", diverse_info_commerce.ID_COMMERCE);
return View(diverse_info_commerce);
}

Using a file uploader in an editor template

I'm working with documents. I've got working CRUD for DocumentViewModel - good so far. There will be other models that have documents as properties. I don't want to repeat myself, so I converted my Edit View of DocumentViewModel into an editor template.
Now I'm working on LeaseViewModel, which has a property LeaseDocument of type DocumentViewModel. The scaffolded Create view pulls the editor template in correctly. However, I get a problem in the POST Create method in the controller. All the simple LeaseViewModel properties are populated, and most of the sub-properties on the LeaseDocument property are populated, but DocumentUpload is null. Any thoughts?
View Models:
public class DocumentViewModel
{
#region Properties
public int? ItemID { get; set; }
[Required(ErrorMessage = "Name is required")]
public string Name { get; set; }
public string Description { get; set; }
[Display(Name = "Version Number")]
public int Version_Number { get; set; }
// TODO: culture code?
[Display(Name = "Document")]
[DataType(System.ComponentModel.DataAnnotations.DataType.Upload)]
public HttpPostedFileBase DocumentUpload { get; set; }
...
}
public class LeaseViewModel
{
#region Properties
public int ItemID { get; set; }
[Display(Name = "Space")]
[Required]
public int SpaceID { get; set; }
[Display(Name = "Status")]
[Required]
public int StatusID { get; set; }
public string StatusText { get; private set; }
[Display(Name = "Type")]
[Required]
public int TypeID { get; set; }
public string TypeText { get; private set; }
public DocumentViewModel LeaseDocument { get; set; }
...
}
Controller:
[Authorize]
public class LeasesController : Controller
{
...
// POST: Lease/Create
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(true)]
public ActionResult Create(LeaseViewModel vm)
{
LeaseItem created = createLeaseVersion(vm);
if (created == null)
return View(vm);
else
return RedirectToAction("Index");
}
...
}
View:
#using CMS.CustomTables;
#using CMS.CustomTables.Types.Tenantportal;
#using CMS.DocumentEngine.Types.Tenantportal;
#model TenantPortal.Models.LeaseViewModel
#{
ViewBag.Title = "Documents";
var emptySpaceOpts = new SelectList(new List<CustomTableItem>(), "ItemID", "Identifier");
var tenantOpts = new SelectList(TenantProvider.GetTenants(), "ItemID", "Display_Name");
var statusOpts = new SelectList(CustomTableItemProvider.GetItems<LeaseStatusItem>(), "ItemID", "Name");
var typeOpts = new SelectList(CustomTableItemProvider.GetItems<LeaseTypeItem>(), "ItemID", "Name");
}
<h2 class="page-title">Create Lease</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.EditorFor(model => model.LeaseDocument)
<div class="form-group">
#Html.LabelFor(model => model.SpaceID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SpaceID, emptySpaceOpts, "(select Property)")
#Html.ValidationMessageFor(model => model.SpaceID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StatusID, statusOpts)
#Html.ValidationMessageFor(model => model.StatusID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TypeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TypeID, typeOpts)
#Html.ValidationMessageFor(model => model.TypeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExecutionDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExecutionDate)
#Html.ValidationMessageFor(model => model.ExecutionDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommenceDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CommenceDate)
#Html.ValidationMessageFor(model => model.CommenceDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ExpirationDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ExpirationDate)
#Html.ValidationMessageFor(model => model.ExpirationDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CanViewCapBudget, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<label>
#Html.RadioButtonFor(model => model.CanViewCapBudget, "true")
Yes
</label>
<label>
#Html.RadioButtonFor(model => model.CanViewCapBudget, "false", htmlAttributes: new { #checked = "checked" })
No
</label>
#Html.ValidationMessageFor(model => model.CanViewCapBudget, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Editor Template for DocumentViewModel
#using TenantPortal.Models
#using CMS.DocumentEngine.Types.Tenantportal
#model DocumentViewModel
#{
var signedOpts = DocumentViewModel.GetSignedOpts();
var propertyOpts = new SelectList(PropertyProvider.GetProperties().Columns("ItemID", "Identifier"), "ItemID", "Identifier");
var tenantOpts = new SelectList(TenantProvider.GetTenants(), "ItemID", "Display_Name");
bool isEdit = ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString() == "Edit";
object uploaderAtts;
int version;
if (isEdit)
{
uploaderAtts = new { #type = "file", #class = "form-control" };
Model.Version_Number += 1;
version = Model.Version_Number;
}
else
{
uploaderAtts = new { #type = "file", #required = "required", #class = "form-control" };
version = 1;
}
}
#Html.HiddenFor(model => model.ItemID)
<div class="form-group row">
<div class="col-sm-12 col-md-6 field">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
<div class="col-sm-12 col-md-6 field">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-12 col-md-6 field">
#Html.LabelFor(model => model.Version_Number, htmlAttributes: new { #class = "control-label" })
#Html.EditorFor(model => model.Version_Number, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly", #Value = version } })
#Html.ValidationMessageFor(model => model.Version_Number, "", new { #class = "text-danger" })
</div>
<div class="col-sm-12 col-md-6 field">
#Html.LabelFor(model => model.DocumentUpload, htmlAttributes: new { #class = "control-label" })
#(isEdit ? Html.Raw(String.Format("<a href='{0}' download='{1}'>{1}</a>", Model.Document_Url, Model.Original_File_Name)) : new HtmlString(""))
#Html.TextBoxFor(model => model.DocumentUpload, uploaderAtts)
#Html.ValidationMessageFor(model => model.DocumentUpload, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-12 col-md-4 field">
#Html.LabelFor(model => model.Signed, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.Signed, signedOpts, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Signed, "", new { #class = "text-danger" })
</div>
<div class="col-sm-12 col-md-4 field">
#Html.LabelFor(model => model.PropertyID, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.PropertyID, propertyOpts, "(none)")
#Html.ValidationMessageFor(model => model.PropertyID, "", new { #class = "text-danger" })
</div>
<div class="col-sm-12 col-md-4 field">
#Html.LabelFor(model => model.TenantID, htmlAttributes: new { #class = "control-label" })
#Html.DropDownListFor(model => model.TenantID, tenantOpts, "(none)")
#Html.ValidationMessageFor(model => model.TenantID, "", new { #class = "text-danger" })
</div>
</div>
If your form is sending a file, you have to set its enctype to multipart/form-data
e.g.
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
Hth...

Auto Populate Fields Based on A Single Field On Tab Out or Keypress

I am using a ASP.NET MVC project created using Entity Framework in Visual Studio 2017. I have a create view for an Employees controller where a user can enter inventory data. I'd like to have the user ID field auto populate data from Active Directory. How do I implement a keypress or tab out or field change event when the username is entered so it triggers a look up and returns and populates specific fields with relevant data?
Here is an idea of what I'm looking at:
Here's some of the CSHTML as is for reference:
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.OfficeId, "Office", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("OfficeId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.OfficeId, "", new { #class = "text-danger" })
</div>
</div>
<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.FullName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FullName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FullName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EquipId, "Equipment", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("EquipId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.EquipId, "", new { #class = "text-danger" })
</div>
</div>
I'm not familiar with ajax and I only know a little bit of javascript, I'd rather try to contain the code to C# though, as all the Active Directory related code is already written.
Could I just add a "Lookup" button next to the User ID field and have them click that to populate? If so how?
It can be done , although with a litte bit of javascript. Like so :
Model :
public class EmployeesViewModel
{
public int SelectedOfficeID { get; set; }
public int SelectedEquipmentID { get; set; }
public int UserID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public List<Office> OfficeList { get; set; }
public List<Equipment> EquipmentList { get; set; }
}
public class Equipment
{
public int EquipmentID { get; set; }
public string EquipmentName { get; set; }
}
public class Office
{
public int OfficeID { get; set; }
public string OfficeName { get; set; }
}
Controller :
public class EmployeesController : Controller
{
public ActionResult Employee()
{
EmployeesViewModel model = new EmployeesViewModel();
SetEquipmentData(model);
SetOfficeData(model);
return View(model);
}
[HttpPost]
public ActionResult Employee(EmployeesViewModel model)
{
SetEquipmentData(model);
SetOfficeData(model);
// remove properties from modelstate in order to get modified values in view
ModelState.Remove("Name");
ModelState.Remove("Phone");
ModelState.Remove("Email");
//SHOULD GET EMPLOYEE DATA FROM DB BASED ON UserID PROPERTY
// dummy data:
model.Name = "John Doe";
model.Phone = "973-548-85965";
model.Email = "John#Company.com";
return View(model);
}
private void SetEquipmentData(EmployeesViewModel model)
{
// dummy data:
model.EquipmentList = new List<Equipment>();
model.EquipmentList.Add(new Equipment(){EquipmentID = 1, EquipmentName="Hammer"});
model.EquipmentList.Add(new Equipment() { EquipmentID = 2, EquipmentName = "Screwdriver" });
model.EquipmentList.Add(new Equipment() { EquipmentID = 3, EquipmentName = "Vise" });
model.EquipmentList.Add(new Equipment() { EquipmentID = 4, EquipmentName = "Plier" });
model.EquipmentList.Add(new Equipment() { EquipmentID = 5, EquipmentName = "Saw" });
}
private void SetOfficeData(EmployeesViewModel model)
{
// dummy data:
model.OfficeList = new List<Office>();
model.OfficeList.Add(new Office() { OfficeID = 10, OfficeName = "Charleston" });
model.OfficeList.Add(new Office() { OfficeID = 20, OfficeName = "Springfield" });
model.OfficeList.Add(new Office() { OfficeID = 30, OfficeName = "Montclair" });
model.OfficeList.Add(new Office() { OfficeID = 40, OfficeName = "Louisville" });
model.OfficeList.Add(new Office() { OfficeID = 50, OfficeName = "Albany" });
}
}
View :
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#using (Html.BeginForm("Employee", "Employees", FormMethod.Post, new { id = "EmployeeForm", name = "EmployeeForm" }))
{
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.SelectedOfficeID, "Office", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SelectedOfficeID, new SelectList(Model.OfficeList, "OfficeID", "OfficeName"))
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UserID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserID, "", new { #class = "text-danger" })
</div>
</div>
<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.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedEquipmentID, "Equipment", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.SelectedEquipmentID, new SelectList(Model.EquipmentList, "EquipmentID", "EquipmentName"))
</div>
</div>
}
</div>
<script type="text/javascript">
$('#UserID').bind('change', function(e) {
document.EmployeeForm.submit();
});
</script>

C# ASP.NET MVC 5 Entity Framework - edit function did not work

Here is my model:
public class Auction
{
[Key]
[Required]
public long Id { get; internal set; }
[Required]
[Display(Name = "Title")]
public string Title { get; set; }
[Required]
[Display(Name = "Description")]
public string Description { get; set; }
[Required]
[Display(Name = "Product Name")]
public string productName { get; set; }
[Required]
[Display(Name = "Product Price")]
public string productPrice { get; set; }
[Required]
[Display(Name = "Auction Start Time")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy MM, dd}", ApplyFormatInEditMode = true)]
public DateTime StartTime { get; set; }
[Required]
[Display(Name = "Auction End Time")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EndTime { get; set; }
[Required]
[DataType(DataType.Currency)]
[Display(Name = "Auction Start Price")]
public decimal StartPrice { get; set; }
[DataType(DataType.Currency)]
[Display(Name = "Auction Current Price")]
public decimal? CurrentPrice { get; set; }
}
}
Here is my DataContext class:
public class AuctionsDataContext : DbContext
{
public DbSet<Auction> Auctions { get; set; }
static AuctionsDataContext()
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AuctionsDataContext>());
}
}
Here is my View :
#model Mohn.Models.Auction
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Auction</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.productName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.productName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.productName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.productPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.productPrice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.productPrice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EndTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EndTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StartPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.StartPrice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.StartPrice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CurrentPrice, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CurrentPrice, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CurrentPrice, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
And here is my Edit part that does not worked in the controller:
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Auction auction = db.Auctions.Find(id);
if (auction == null)
{
return HttpNotFound();
}
return View(auction);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,Description,productName,productPrice,StartTime,EndTime,StartPrice,CurrentPrice")] Auction auction)
{
if (ModelState.IsValid)
{
db.Entry(auction).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(auction);
}
The problem is, when I pass my Auction id in the URL, then it will retrieve data to the view except start time. And I cannot submit the details, it will cause an exception.
Start time will not display on my view,
I am showing a screenshot here:
enter image description here
Even if I submit the start date with given details on my View, it will throw an exception
The screenshot shows it:
enter image description here
An exception of type 'System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted
Please help me to solve this, and I am new to Asp.net MVC 5, Entity Framework, I want to know what exactly happen...
Thanks your attention....and help..:)
I guess the problem is in the ID...when I debug the program it is passed 0 to the controller...How to change this?...
You need to remove internal for setter method id property. Due to internal model binder was unable to set value to it
[Key]
[Required]
public long Id { get; internal set; }
Change it to
[Key]
[Required]
public long Id { get; set; }
First of all your Start Time format annotation is "{0:yyyy MM, dd}" that seems "{0:yyyy-MM-dd}" is true. after that because of your [DataType(DataType.Currency)] annotation and problem to transfer this field data, this exception has occured.

Categories