如何从视图中上传或下载文件而无需进入模型

时间:2018-07-23 13:42:42

标签: c# razor asp.net-mvc-5

我正在开发一个依赖现有SQL Server数据库的应用程序。我已经在Visual Studio中使用实体框架代码优先方法创建了模型,控制器和创建视图。目前,该代码适用于所有字段,并且接受null表示应包含外部文件路径的字段(不在DB中)。

模型:

    namespace Centurion.Models
    {
        using System;
        using System.Collections.Generic;
        using System.ComponentModel;
        using System.ComponentModel.DataAnnotations;
        using System.ComponentModel.DataAnnotations.Schema;
        using System.Data.Entity.Spatial;

        [Table("Fontane")]
        public partial class Fontane
        {
            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
            public Fontane()
            {
                Interventi = new HashSet<Interventi>();
            }

            [Key]
            //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
            public int FontanaID { get; set; }

            private string _CodificaSIMU;

            [StringLength(20)]
            public string CodificaSIMU
            {
                get
                {
                    if (string.IsNullOrEmpty(_CodificaSIMU))
                    {
                        return _CodificaSIMU;
                    }
                    return _CodificaSIMU.ToUpper();
                }
                set
                {
                    _CodificaSIMU = value;
                }
            }
            //public string CodificaSIMU { get; set; }

            [Required]
            [StringLength(255)]
            public string Nome { get; set; }

            [StringLength(255)]
            public string Indirizzo { get; set; }

            public int? Municipio { get; set; }

            [Required]
            public double Latitudine { get; set; }

            [Required]
            public double Longitudine { get; set; }

            [Required]
            public int TipoFontana { get; set; }

            [Required]
            public int TipoImpianto { get; set; }

            [Required]
            public int Frequenza { get; set; }

            [Required]
            public bool Svuotamento { get; set; }

            public bool? Active { get; set; }

            public bool? Allarme { get; set; }

            [StringLength(255)]
            public string Foto { get; set; }

            [StringLength(255)]
            public string Allegato1 { get; set; }

            [StringLength(255)]
            public string Allegato2 { get; set; }

            public string Note { get; set; }

            [Required]
            public int UserIDCrea { get; set; }

            [Required]
            public DateTime DataCrea { get; set; }

            [Required]
            public int UserIDModifica { get; set; }

            [Required]
            public DateTime DataModifica { get; set; }

            public virtual Municipi Municipi { get; set; }

            public virtual TipiFontana TipiFontana { get; set; }

            public virtual Impianto Impianto { get; set; }

            public virtual Utenti Utenti { get; set; }

            public virtual Utenti Utenti1 { get; set; }

            [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
            public virtual ICollection<Interventi> Interventi { get; set; }

        }

        public class FontaneFiles
        {
            [DataType(DataType.Upload)]
            [Display(Name = "Upload Foto")]
            public string FotoFile { get; set; }

            [DataType(DataType.Upload)]
            [Display(Name = "Upload Allegato1")]
            public string All1File { get; set; }

            [DataType(DataType.Upload)]
            [Display(Name = "Upload Allegato2")]
            public string All2File { get; set; }
        }
    }

您可以看到,由于数据库中的相对表仅包含服务器中路径的字符串,因此我添加了第二个类来上传文件。

这是我的控制器的代码,除了文件上传部分外,它的工作正常:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Crea([Bind(Include = "FontanaID,CodificaSIMU,Nome,Indirizzo,Municipio,Latitudine,Longitudine,TipoFontana,TipoImpianto,Frequenza,Svuotamento,Foto,Allegato1,Allegato2,Note")] Fontane fontane)
        //public ActionResult Crea([Bind(Include = "FontanaID,CodificaSIMU,Nome,Indirizzo,Municipio,Latitudine,Longitudine,TipoFontana,TipoImpianto,Frequenza,Svuotamento,Active,Allarme,Foto,Allegato1,Allegato2,Note,UserIDCrea,DataCrea,UserIDModifica,DataModifica")] Fontane fontane)
    {
        // to be replaced in production mode with logged user
        fontane.UserIDCrea = cUser;
        fontane.UserIDModifica = cUser;

        // set date as NOW
        fontane.DataCrea = DateTime.Now;
        fontane.DataModifica = DateTime.Now;
        // no allarm when creating
        fontane.Allarme = false;
        // active when creating
        fontane.Active = true;

        fontane.Latitudine = Convert.ToDouble(fontane.Latitudine);
        fontane.Longitudine = Convert.ToDouble(fontane.Longitudine);

        if (ModelState.IsValid)
        {
            try
            {
                db.Fontane.Add(fontane);
                db.SaveChanges();
                return RedirectToAction("Indice");
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError(string.Empty, "Fontana esistente!");
            }
            catch (Exception ex)
            {
                return View("Error", new HandleErrorInfo(ex, "Fontane", "Crea"));
            }
            return View();
        }

        ViewBag.TipoImpianto = new SelectList(db.Impianto, "ImpiantoID", "Impianto1", fontane.TipoImpianto);
        ViewBag.Municipio = new SelectList(db.Municipi, "MunicipioID", "Municipio", fontane.Municipio);
        ViewBag.TipoFontana = new SelectList(db.TipiFontana, "TipoID", "Descrizione", fontane.TipoFontana);
        ViewBag.UserIDCrea = new SelectList(db.Utenti, "UserID", "UserName", fontane.UserIDCrea);
        ViewBag.UserIDModifica = new SelectList(db.Utenti, "UserID", "UserName", fontane.UserIDModifica);
        return View(fontane);
    }

视图:

    @model Centurion.Models.Fontane

    @{
        ViewBag.Title = "Crea";
    }

    <h2>Aggiungi Fontana</h2>

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

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

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

        <fieldset>
            <legend>Ubicazione</legend>

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

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

            <div class="form-group">
                @Html.LabelFor(model => model.Latitudine, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Latitudine, new
               {
                   htmlAttributes = new
                   {
                       placeholder = "Latitudine = 41,..... (con la virgola)",
                       @class = "form-control"
                   }
               })
                    @Html.ValidationMessageFor(model => model.Latitudine, "", new { @class = "text-danger" })
                </div>
            </div>

            <div class="form-group">
                @Html.LabelFor(model => model.Longitudine, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model.Longitudine, new
               {
                   htmlAttributes = new
                   {
                       placeholder = "Longitudine = 12,..... (con la virgola)",
                       @class = "form-control"
                   }
               })
                    @Html.ValidationMessageFor(model => model.Longitudine, "", new { @class = "text-danger" })
                </div>
            </div>
        </fieldset>

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

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

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

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

        @Html.HiddenFor(m => m.Active)
        @Html.HiddenFor(m => m.Allarme)

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

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

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

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

        @Html.HiddenFor(m => m.UserIDCrea)
        @Html.HiddenFor(m => m.DataCrea)
        @Html.HiddenFor(m => m.UserIDModifica)
        @Html.HiddenFor(m => m.DataModifica)

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Crea" class="btn btn-default" />
            </div>
        </div>
    </div>
    }

    <div>
        @Html.ActionLink("Elenco Fontane", "Indice")
    </div>

我无法更改数据库表,但是我需要找到一种触发图像和其他文件(应为pdf或Excel)上传的方法。文件将存储在app_data文件夹的子文件夹中。 如果将文件添加到Fontane的同一类中,则会出现表错误。我试图将两个类与一个元组结合在一起,但是我不知道如何在Controller中管理它们。任何帮助将不胜感激。

0 个答案:

没有答案