asp.net MVC upload file name is System.Web.HttpPostedFileWrapper - c#

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();
}
}

Related

Input type file not showing ASP.NET

I have this model:
public class PostAddRequest
{
public string Title { get; set; }
public string Description { get; set; }
public string Content { get; set; }
public int CategoryId { get; set; }
public string FeaturedImagePath { get; set; }
public HttpPostedFileBase FeaturedImage { get; set; }
public List<string> GalleryImagesPath { get; set; }
public HttpPostedFileBase[] GalleryImages { get; set; }
}
Controller:
[HttpGet]
public ActionResult Create()
{
return View(new PostAddRequest());
}
View:
#model BusinessObjects.Requests.PostAddRequest
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Post", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>PostAddRequest</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<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.Content, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Content, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Content, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CategoryId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CategoryId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CategoryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FeaturedImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.FeaturedImage, new { type = "file", htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FeaturedImage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GalleryImages, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.GalleryImages, "", new { #type = "file", #multiple = "multiple" })
#Html.ValidationMessageFor(model => model.GalleryImages, "", 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")
}
I'm getting this error: Compiler Error Message: CS1061: 'PostAddRequest' does not contain a definition for 'GalleryImages' and no accessible extension method 'GalleryImages' accepting a first argument of type 'PostAddRequest' could be found (are you missing a using directive or an assembly reference?)
I want to upload an image for FeaturedImage and multiple images for GalleryImages, but for some reason I'm getting the above error. Any idea on how to fix this?
you should use List<IFormFile> for multiple files.
public List<IFormFile> GalleryImagesPath { get; set; }

(C#) How do I send an image file from an ASP.NET MVC 5 web form to my SQL database?

I'm trying to insert an image file that a user uploads from a web form into my SQL database so that it shows up on my Index page next to their information. All of the other information sends and shows up on the page, but the photo simply won't save to the database or display on the Index. Could someone help me figure out what I have wrong?
FacultyController.cs
using POS.Datos;
using POS.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using System.IO ;
namespace POS.Controllers
{
public class FacultyController : Controller
{
FacultyAdmin admin = new FacultyAdmin();
// GET: Faculty
public ActionResult Index()
{
return View(admin.Consultar());
}
[HttpGet]
public ActionResult Nuevo()
{
ViewBag.Meal_Plan = GetPlanesSelect();
admin.Consultar();
return View();
}
[HttpPost]
[ActionName("Guardar")]
public ActionResult NuevoPost(Faculty empleado)
{
if (ModelState.IsValid)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
admin.Consultar();
context.Faculties.Add(empleado);
context.SaveChanges();
ViewBag.mensaje = "Informacion Guardada";
return RedirectToAction("Index");
}
return View(empleado);
}
public ActionResult Guardar() // HTTP GET
{
ViewBag.mensaje = "";
ViewBag.Meal_Plan = GetPlanesSelect();
return View();
}
[HttpGet]
public ActionResult Editar(int id)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
ViewBag.Meal_Plan = GetPlanesSelect();
return View(empleado);
}
[HttpPost]
[ActionName("Editar")]
public ActionResult Editar(Faculty empleado)
{
if (ModelState.IsValid)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
context.Entry(empleado).State = EntityState.Modified;
context.SaveChanges();
return RedirectToAction("Index");
}
return View(empleado);
}
public IEnumerable<SelectListItem> GetPlanesSelect()
{
using (Cafeteria_POSEntities Context = new Cafeteria_POSEntities())
{
return Context.Plans.Select(plan => new SelectListItem { Value = plan.Plan_Name, Text = plan.Plan_Name }).ToList();
}
}
[HttpGet]
public ActionResult Eliminar(int id)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
return View(empleado);
}
[HttpPost]
[ActionName("Eliminar")]
public ActionResult EliminarConfirm(int id)
{
Cafeteria_POSEntities context = new Cafeteria_POSEntities();
Faculty empleado = context.Faculties.Single(x => x.Employee_ID == id);
context.Faculties.Remove(empleado);
context.SaveChanges();
return RedirectToAction("Index");
}
// Saves user-uploaded image to the database //
public string Upload_Image(HttpPostedFileBase image_file)
{
Random r = new Random() ;
String path = "-1" ;
int random = r.Next() ;
if (image_file != null && image_file.ContentLength > 0)
{
string extension = Path.GetExtension(image_file.FileName) ;
if (extension.ToLower().Equals(".jpg") || extension.ToLower().Equals(".jpeg") || extension.ToLower().Equals(".png"))
{
try
{
path = Path.Combine(Server.MapPath("~/Content/Images") , random + Path.GetFileName(image_file.FileName)) ;
image_file.SaveAs(path) ;
path = "~/Content/Images/" + random + Path.GetFileName(image_file.FileName) ;
}
catch (Exception ex)
{
path = "-1" ;
}
}
else
{
Response.Write("<script>alert('Images may only be of the following formats: .jpg , .jpeg , and .png .');</script>") ;
}
}
else
{
Response.Write("<script>alert('Please select an image to upload!');</script>");
path = "-1" ;
}
return path ;
}
}
}
Faculty.cs
namespace POS.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
public partial class Faculty
{
[DisplayName("Employee ID:")]
public int Employee_ID { get; set; }
[DisplayName("Organization Name:")]
public string Organization_Name { get; set; }
[DisplayName("First Name:")]
public string First_Name { get; set; }
[DisplayName("Last Name:")]
public string Last_Name { get; set; }
[DisplayName("Job Title:")]
public string Job_Title { get; set; }
[DisplayName("Email:")]
public string Email { get; set; }
[DisplayName("Photo:")]
public byte[] Photo { get; set; }
[DisplayName("Address:")]
public string Address { get; set; }
[DisplayName("Phone Number:")]
public string Phone_Number { get; set; }
[DisplayName("Meal Plan:")]
public string Meal_Plan { get; set; }
[DisplayName("Meal Plan Status:")]
public bool Meal_Plan_Status { get; set; }
[DisplayName("Plan:")]
public virtual Plan Plan { get; set; }
}
}
Guardar.cshtml
#model POS.Models.Faculty
#{
ViewBag.Title = "Add Faculty Member";
}
<h2>Faculty Member</h2>
<h4>Add a new faculty member</h4>
<!-- Metodo "Nuevo", Controlador "Producto", Accion "HTTP POST" -->
#using (Html.BeginForm("Guardar", "Faculty", FormMethod.Post , new {enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label class="control-label col-md-2" for="Organization_Name">Organization Name</label>
<div class="col-md-10">
#Html.EditorFor(model => model.Organization_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Organization_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.First_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10" for="First_Name">
#Html.EditorFor(model => model.First_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.First_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Last_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Last_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Last_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Job_Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Job_Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Job_Title, "", 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.Photo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Photo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Photo, "", new { #class = "text-danger" })
<input type="file" id="image_file" name="file"/>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone_Number, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone_Number, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone_Number, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Meal_Plan, "Meal_Plan", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Meal_Plan", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Meal_Plan, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Meal_Plan_Status, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.Meal_Plan_Status)
#Html.ValidationMessageFor(model => model.Meal_Plan_Status, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Guardar" class="btn btn-default" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<font color="green">#ViewBag.mensaje</font>
</div>
</div>
</div>
}
<!--
<h4><b>Personal Information</b></h4>
Name:
Email Address:
<!--
Date of Birth:
-->
<!--
Gender:
Male
Female
Phone Number:
Address (Optional):
<h4><b>Institutional Information</b></h4>
Organization:
Language Institute
Keiser University
<br />
Job Title:
Administrator
Cafeteria Team Member
Cleaning Crew Team Member
Coach
Instructor
I.T. Team Member
Library Team Member
Security Guard
<br />
Meal Plan:
No Plan
A
B
C
Active?
-->
#Html.ActionLink("Return to Faculty Index", "Index")
#section Scripts {
#Scripts.Render("\~/bundles/jqueryval")
}
I've already tried going through this video (https://www.youtube.com/watch?v=-jNWVKoYhaM), but, for some reason, it still doesn't work (though I can now save images to ~/Content/Images and the program actually seems like it wants to pull an image from said file).
You're storing the images to a folder on your server, which is fine. But you also seem to expect the image file to be stored in the database as well. If you're going to store the image files in the file system and not in the database then what you really want in the database is the path to the image file so you can reference that in the HTML. As you are writing the photo to the file system you should also update the database with the path to the file and then in your HTML you can generate an <img> tag to load the file from the file system.
You should update the db during Upload_Image(). Currently it's only saving the image file to the file system.
try
{
path = Path.Combine(Server.MapPath("~/Content/Images") , random + Path.GetFileName(image_file.FileName)) ;
image_file.SaveAs(path) ;
/* SAVE path TO DB HERE */
}
catch (Exception ex)
{
path = "-1" ;
}
}

Uploading files from MVC Edit Page/View

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);
}

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...

Categories