Uploading files (images) in ASP.net does not send the image

Asked

Viewed 233 times

0

I can’t send images (banners) in my Asp.net application

My controller :

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ValidateInput(false)]
    public ActionResult Save([Bind(Include = "BannerId,DatHorLan,Tit,Atv")] Banner banner)
    {
        try
        {
            banner.DatHorLan = DateTime.Now;
            banner.UsuarioId = 1;
            if (ModelState.IsValid)
            {
                // Se foi enviado um arquivo com mais do que 0 bytes:
                if (banner.File != null && banner.File.ContentLength > 0)
                {
                    // Extraindo nome do arquivo
                    var fileName = Path.GetFileName(banner.File.FileName);

                    var path = Path.Combine(Server.MapPath("/Uploads/Img/Banners"), fileName);
                    banner.File.SaveAs(path);

                    banner.Img = fileName;
                    ModelState.Remove("Img");
                }
                if (banner.BannerId == 0)
                {
                    banner.DatHorLan = DateTime.Now;
                    db.Banners.Add(banner);
                }
                else
                {
                    db.Entry(banner).State = EntityState.Modified;
                }
                db.SaveChanges();
                ViewBag.Message = "Registro gravado com sucesso.";
            }
        }
        catch (DataException)
        {
            ViewBag.Message = "Ocorreu um erro ao gravar o registro.";
        }
        return View("Form", banner);
    }

My Model :

[Table("Banners")]
public class Banner
{
    [Key]
    [Column("BannerId")]
    [Display(Name = "Banner")]
    public int BannerId { get; set; }

    [Required]
    [Column("Tit")]
    [Display(Name = "Título")]
    public string Tit { get; set; }

    [Required]
    [Column("Atv")]
    [Display(Name = "Atívo")]
    public int Atv { get; set; }

    [Column("Img")]
    [Display(Name = "Imagem")]
    public string Img { get; set; }

    [Display(Name = "Imagem")]
    [NotMapped]
    public HttpPostedFileBase File { get; set; }

    [Column("DatHorLan")]
    [Display(Name = "Data/Hora")]
    [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy hh:mm:ss}", ApplyFormatInEditMode = true)]
    public DateTime DatHorLan { get; set; }

    [Column("UsuarioId")]
    [Display(Name = "Usuário")]
    public int UsuarioId { get; set; }
    [Display(Name = "Usuário")]
    public virtual Usuario Usuario { get; set; }

}

My HTML (View)

@model FiscoCorretora.Areas.Admin.Models.Banner

@{
    ViewBag.Title = "Páginas";
    Layout = "~/Areas/Admin/Views/Shared/_Layout.cshtml";
}

<div class="box box-danger">
    <div class="box-header with-border">
        @if (Model.BannerId == 0)
        {
            <h3 class="box-title">Banner - Novo</h3>
        }
        else
        {
            <h3 class="box-title">Banner - Alterando</h3>
        }
    </div>
    @using (Html.BeginForm("save","banners", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.HiddenFor(model => model.BannerId)
        @Html.HiddenFor(model => model.DatHorLan)

        <div class="box-body">
            <div class="form-horizontal">
                <div class="form-group">
                    @Html.LabelFor(model => model.Tit, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.EditorFor(model => model.Tit, new { htmlAttributes = new { @class = "form-control input-sm" } })
                        @Html.ValidationMessageFor(model => model.Tit, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(model => model.Atv, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.DropDownList("Atv", new List<SelectListItem>
                                         {
                                            new SelectListItem{ Text="Não", Value = "0" },
                                            new SelectListItem{ Text="Sim", Value = "1" }
                                         }, new { @class = "form-control" })

                        @Html.ValidationMessageFor(model => model.Atv, "", new { @class = "text-danger" })
                    </div>
                </div>
                <div class="form-group">
                    @Html.LabelFor(model => model.File, htmlAttributes: new { @class = "control-label col-md-2" })
                    <div class="col-md-10">
                        @Html.TextBoxFor(model => model.File, new { type = "file", @class = "form-control" })            
                        @Html.ValidationMessageFor(model => model.File)
                    </div>
                </div>
                <label class="text-sm text-red pull-right">@ViewBag.Message</label>
            </div>
        </div>
        <div class="box-footer">
            <a href="/admin/banners" id="btn-voltar" class="btn btn-primary btn-sm pull-right" title="Volta pra tela de pesquisa.">
                <i class="fa fa-undo fa-lg"></i>&nbsp;Voltar
            </a>
            <button type="submit" id="btn-gravar" value="Gravar" class="btn btn-primary btn-sm pull-right" title="Grava o registro." style="margin-right: 5px;">
                <i class="fa fa-floppy-o fa-lg" aria-hidden="true"></i>&nbsp;Gravar
            </button>
        </div>
    }
</div>

@section Scripts{
    <script type="text/javascript">
        $(document).ready(function () {
            CKEDITOR.replace('Txt')
            $('.textarea').wysihtml5()
        });
    </script>
}

Save the log to the bank and everything else, but do not send the image In control :

if (banner.File != null && banner.File.ContentLength > 0)

Always ta null !

1 answer

0


This form lies within another form?

If yes remove new { enctype = "multipart/form-data" } and add to the parent form.

  • It worked! Thank you. And I’m sorry for the delay.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.