MVC文件上载将详细信息保存到数据库和文件存储

时间:2018-07-16 13:48:15

标签: c# asp.net-mvc file model-view-controller upload

我在一个视图中使用了该功能,并在其他两个视图中进行了精确复制-但是新视图将无法使用...

该视图创建文件结构,上载该文件,并在数据库中记录2个条目。与文件有关,上载视图中的所有其他字段保存信息-FileDesc和FileName字段返回空白。

我肯定想念一些明显的东西...

型号:

namespace inventIT.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web;
public partial class EquipmentReceipt
{
    public int RecordID { get; set; }
    [Required]
    [Display(Name = "Staff Member")]
    public string AssessorID { get; set; }
    [Required]
    [Display(Name = "Equipment Type")]
    public string EquipmentType { get; set; }

    [Display(Name = "Serial Number (Where Required)")]
    public string EquipmentSerial { get; set; }

    [Display(Name = "Computer AD Name / IMEI Number")]
    public string ADIMEI { get; set; }
    [Required]
    [Display(Name = "Added By")]
    public string ITAssignedBy { get; set; }
    [Required]
    [Display(Name = "Date Assigned")]
    public Nullable<System.DateTime> DateAssigned { get; set; }

    [Display(Name = "Date Withdrawn")]
    public Nullable<System.DateTime> DateWithdrawn { get; set; }
    [Display(Name = "Notes")]
    public string Notes { get; set; }

    [Display(Name = "File Attachment")]
    public string FileDesc { get; set; }
    [Display(Name = "File Attachment")]
    public string FileName { get; set; }
    public string Extension { get; set; }
    [DisplayFormat(DataFormatString = "{0:dd-mm-yyyy}")]
    public DateTime Date1 { get; set; }
    public Nullable<int> FileID { get; set; }
    public string CreateFolder { get; set; }

    public virtual ADIMEILookup ADIMEILookup { get; set; }
    public virtual Lookup Lookup { get; set; }
    public virtual ITTeamLookup ITTeamLookup { get; set; }
    public virtual StaffMemberLookup StaffMemberLookup { get; set; }
}
}

控制器:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using inventIT.Models;

namespace inventIT.Controllers
{
public class EquipmentReceiptsController : Controller
{
    private HAWKTRAINING_INVENTITEntities db = new HAWKTRAINING_INVENTITEntities();

    // GET: EquipmentReceipts
    public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? PageSize)
    {


        ViewBag.searchString = "";
        ViewBag.CurrentSort = sortOrder;
        ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
        ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

        if (searchString != null)
        {
            page = 1;
        }
        else
        {
            searchString = currentFilter;
        }

        ViewBag.CurrentFilter = searchString;

        var AssessorIDs = from s in db.EquipmentReceipts




                          select s;
        if (!String.IsNullOrEmpty(searchString))
        {
            AssessorIDs = AssessorIDs.Where(s => s.AssessorID.Contains(searchString) || searchString == null || searchString == "");
        }
        switch (sortOrder)
        {
            case "name_desc":
                AssessorIDs = AssessorIDs.OrderByDescending(s => s.AssessorID);
                break;
            case "Date":
                AssessorIDs = AssessorIDs.OrderBy(s => s.DateAssigned);
                break;
            case "date_desc":
                AssessorIDs = AssessorIDs.OrderByDescending(s => s.DateAssigned);
                break;
            default:  // Name ascending 
                AssessorIDs = AssessorIDs.OrderBy(s => s.AssessorID);
                break;
        }
        var equipmentReceipts = db.EquipmentReceipts.Include(e => e.ADIMEILookup).Include(e => e.Lookup).Include(e => e.ITTeamLookup).Include(e => e.StaffMemberLookup);
        return View(db.EquipmentReceipts.Where(s => s.AssessorID.Contains(searchString) || searchString == null || searchString == "").OrderByDescending(c => c.AssessorID).ToList());
    }

    // GET: EquipmentReceipts/Details/5
    public ActionResult Details(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        EquipmentReceipt equipmentReceipt = db.EquipmentReceipts.Find(id);
        if (equipmentReceipt == null)
        {
            return HttpNotFound();
        }
        return View(equipmentReceipt);
    }

    // GET: EquipmentReceipts/Create
    public ActionResult Create()
    {
        ViewBag.ADIMEI = new SelectList(db.ADIMEILookups, "ADIMEIID", "ADIMEI");
        ViewBag.EquipmentType = new SelectList(db.Lookups.Where(c => c.Fieldname == "EquipmentType"), "KeyID", "Title");
        ViewBag.ITAssignedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
        ViewBag.AssessorID = new SelectList(db.StaffMemberLookups, "StaffMemberID", "StaffMember");
        return View();
    }

    // POST: EquipmentReceipts/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "RecordID,AssessorID,EquipmentType,EquipmentSerial,ADIMEI,ITAssignedBy,DateAssigned,DateWithdrawn,Notes,ComputerModel,FileDesc")] EquipmentReceipt equipmentReceipt)
    {

        // POST: File Upload Script Starts
        if (ModelState.IsValid)
        {
            List<EquipmentReceipt> fileDetails = new List<EquipmentReceipt>();
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    EquipmentReceipt fileDetail = new EquipmentReceipt()
                    {
                        FileName = fileName,
                        Extension = Path.GetExtension(fileName)
                    };
                    fileDetails.Add(fileDetail);
                    var Date = DateTime.Now;
                    var Date2 = Date.ToString("dd-MM-yyyy");
                    var Date3 = Date.ToString("HHmmss");



                    string pathToCreate = Path.Combine("~/App_Data/uploads/Equipment_Receipts", Date2, Date3);

                    bool exists = System.IO.Directory.Exists(Server.MapPath(pathToCreate));
                    if (!exists)
                        System.IO.Directory.CreateDirectory(Server.MapPath(pathToCreate));
                    var path2 = Path.Combine(Server.MapPath(pathToCreate), Date3 + "_" + fileDetail.FileName);
                    equipmentReceipt.FileDesc = path2;
                    equipmentReceipt.FileName = Date3 + "_" + fileDetail.FileName;
                    System.IO.Directory.Exists(pathToCreate);
                    file.SaveAs(equipmentReceipt.FileDesc);
                }
            }


            db.EquipmentReceipts.Add(equipmentReceipt);

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        if (ModelState.IsValid)
        {
            try
            {
                db.EquipmentReceipts.Add(equipmentReceipt);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return View("Error", new HandleErrorInfo(ex, "EquipmentReceipt", "Create"));
            }
        }
        // POST: File Upload Script Ends





        ViewBag.ADIMEI = new SelectList(db.ADIMEILookups, "ADIMEIID", "ADIMEI");
        ViewBag.EquipmentType = new SelectList(db.Lookups.Where(c => c.Fieldname == "EquipmentList"), "KeyID", "Title");
        ViewBag.ITAssignedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
        ViewBag.AssessorID = new SelectList(db.StaffMemberLookups, "StaffMemberID", "StaffMember");
        return View(equipmentReceipt);
    }

    // GET: EquipmentReceipts/Edit/5
    public ActionResult Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        EquipmentReceipt equipmentReceipt = db.EquipmentReceipts.Find(id);
        if (equipmentReceipt == null)
        {
            return HttpNotFound();
        }
        ViewBag.ADIMEI = new SelectList(db.ADIMEILookups, "ADIMEIID", "ADIMEI");
        ViewBag.EquipmentType = new SelectList(db.Lookups.Where(c => c.Fieldname == "EquipmentList"), "KeyID", "Title");
        ViewBag.ITAssignedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
        ViewBag.AssessorID = new SelectList(db.StaffMemberLookups, "StaffMemberID", "StaffMember");
        return View(equipmentReceipt);
    }



    // GET: EquipmentReceipts/Delete/5
    public ActionResult Delete(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        EquipmentReceipt equipmentReceipt = db.EquipmentReceipts.Find(id);
        if (equipmentReceipt == null)
        {
            return HttpNotFound();
        }
        return View(equipmentReceipt);
    }

    // POST: EquipmentReceipts/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public ActionResult DeleteConfirmed(int id)
    {
        EquipmentReceipt equipmentReceipt = db.EquipmentReceipts.Find(id);
        db.EquipmentReceipts.Remove(equipmentReceipt);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
}
}

查看

@model inventIT.Models.EquipmentReceipt

@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Equipment Receipts</h2>

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Create</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
    @Html.LabelFor(model => model.AssessorID, "Staff Member", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("AssessorID", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.AssessorID, "", new {    @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.EquipmentType, "Equipment Type", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("EquipmentType", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.EquipmentType, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.ADIMEI, "Computer AD Name/IMEI", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("ADIMEI", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ADIMEI, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.EquipmentSerial, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.EquipmentSerial, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.EquipmentSerial, "", new { @class = "text-danger" })
    </div>
</div>





<div class="form-group">
    @Html.LabelFor(model => model.DateAssigned, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DateAssigned, new { htmlAttributes = new { @class = "form-control jqueryui-marker-datepicker" } })
        @Html.ValidationMessageFor(model => model.DateAssigned, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.DateWithdrawn, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.DateWithdrawn, new { htmlAttributes = new { @class = "form-control jqueryui-marker-datepicker" } })
        @Html.ValidationMessageFor(model => model.DateWithdrawn, "", new { @class = "text-danger" })
    </div>
</div>

<div class="form-group">
    @Html.LabelFor(model => model.Notes, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.ITAssignedBy, "ITAssignedBy", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("ITAssignedBy", null, htmlAttributes: new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.ITAssignedBy, "", new { @class = "text-danger" })
    </div>
</div>
<div class="form-group">
    @Html.LabelFor(model => model.FileDesc, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.HiddenFor(x => x.FileDesc)
        <input type="file" name="file3" id="file" />
    </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>

1 个答案:

答案 0 :(得分:0)

请在您的表单标签中添加新的{enctype =“ multipart / form-data”}

@using (Html.BeginForm("Create", "EquipmentReceipts", FormMethod.Post, new {enctype = "multipart/form-data" }))