0

I am getting an error while uploading a file, I have try to google a lot for the same problem but failed to get any correct solution. please help me. I am attaching my code and error. I am using asp.net 2015 and sql server management 2008 My Database table is something look like this

P_Id int Title varchar(50) Category varchar(50) Description varchar(50) Files image(50)

This is the image of my error.

This is my controller

    [HttpPost]
    public ActionResult FileUpload(Project pro, HttpPostedFileBase file)
    {
        bool Status = false;
        String message = "";
        MyProjectsEntities db = new MyProjectsEntities();

            var file = Request.Files[0];

            try
            {
                if (file != null && file.ContentLength > 0)
                {
                    var content = new byte[file.ContentLength];
                    file.InputStream.Read(content, 0, file.ContentLength);
                    pro.Files = content;
                    db.Projects.Add(pro);
                    db.SaveChanges();
                    message = "Success";
                    Status = true;
                }

            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    message = " Entity of type \"{0}\" in state \"{1}\" has the following validation errors:" + eve.Entry.Entity.GetType().Name + " " + eve.Entry.State;
                    //Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                    //    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        message = "- Property: \"{0}\", Error: \"{1}\"" + ve.PropertyName + " " + ve.ErrorMessage;
                        //Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                        //    ve.PropertyName, ve.ErrorMessage);
                    }
                }
                //throw;
            }


        ViewBag.Message = message;
        ViewBag.Status = Status;
        return RedirectToAction("FileUpload");
    }

This is my model

using System;
using System.Collections.Generic;
namespace MyProjects.Models
{   
public partial class Project
{
    public int P_ID { get; set; }
    public string Title { get; set; }
    public string Category { get; set; }
    public string Description { get; set; }
    public byte[] Files { get; set; }
}}

This is my view

@model MyProjects.Models.Project
@{
      ViewBag.Title = "FileUpload";
}
<h2>FileUpload</h2>
@if (ViewBag.Status != null && Convert.ToBoolean(ViewBag.Status))
{
     if (ViewBag.Message != null)
     {
          <div class="alert alert-success">
          <strong>Success! </strong>@ViewBag.Message
          </div>
     }
}
@using (Html.BeginForm()) 
{
     @Html.AntiForgeryToken() 
     <div class="form-horizontal">
     <h4>Project</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.Category, htmlAttributes: new { @class 
          = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Category, new { htmlAttributes = 
               new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Category, "", 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.Files, htmlAttributes: new { @class = 
               "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.Files, "", new { @type = "file", 
                  @multiple = "multiple" })
            @Html.ValidationMessageFor(model => model.Files, "", 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>
if (ViewBag.Message != null)
{
    <div class="alert alert-danger">
        <strong>Error! </strong>@ViewBag.Message
    </div>
}
}

 <div>
  @Html.ActionLink("Back to List", "Index")
  </div>

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

This is my view model

namespace MyProjects.Models
{
[MetadataType(typeof(ProjectMetadata))]
public partial class Project
{

}

public class ProjectMetadata
{
    [Required(ErrorMessage = "The {0} field is required!")]
    public string Title { get; set; }

    [Required(ErrorMessage = "The {0} field is required!")]
    public string Category { get; set; }

    [Required(ErrorMessage = "The {0} field is required!")]
    public string Description { get; set; }

    [Required(ErrorMessage = "The {0} field is required!")]
    [DataType(DataType.Upload)]
    public IEnumerable<HttpPostedFileBase> Files { get; set; }
}
 }
Hetaram
  • 13
  • 1
  • 4
  • Show your model. Your binding a file input to a property which is clearly not `HttpPostedFileBase` (which it needs to be). –  Oct 07 '17 at 05:24
  • I have already added my model code in my post – Hetaram Oct 07 '17 at 05:31
  • I am not getting your point. Can you elaborate it. – Hetaram Oct 07 '17 at 05:37
  • Use a view model. It will contain a property `public IEnumerable Files { get; set; }` plus the other properties you need (your editing data so ALWAYS use a view model). Then you can delete your `HttpPostedFileBase file` parameter since the view model property will be correctly bound (and remove the `if (Request.Files != null && Request.Files.Count == 1)` - you check the model property, not `Request.Files`) –  Oct 07 '17 at 05:40
  • But `&& Request.Files.Count == 1` makes no sense either since you have made the file input `multiple="multiple"` which is for selecting one or **more** files. If you only want one file, the remove the `multiple="multiple"` and make the view model property `HttpPostedFileBase File` –  Oct 07 '17 at 05:41
  • I have edited my code as per your suggestion but still getting same error. I have edited my post as per new code with my view model – Hetaram Oct 07 '17 at 05:53
  • That is not a view model! - Create a new class (say) `class ProjectVM` in a separate folder named say `ViewModels` and use that class in the view. - [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Oct 07 '17 at 05:56
  • Finally solved. Thank you for your help. It's really a great help. – Hetaram Oct 08 '17 at 05:53

0 Answers0