在asp.net mvc 5中,HttpPostedFileBase ImageUpload始终为null

时间:2015-09-23 20:17:56

标签: c# asp.net asp.net-mvc asp.net-mvc-4

我尝试在aps.net mvc 5中创建一个项目,但是我无法在我的本地目录中保存图像...我的实体(Perfil)的属性:(HttpPostedFileBase ImageUpload)始终为null 翻译成英文:Profile = Perfil

有人能帮助我吗?

。我的实体:

[Table("Perfil")]
public class Perfil
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public int idPerfil { get; set; }

    [Required]
    [ForeignKey("Usuario")]
    public int idUsuario { get; set; }

    [Required]
    [ForeignKey("Genero")]
    public int idGenero { get; set; }

    [DisplayName("Descrição:")]
    public string descricao { get; set; }

    public string linkMultimidia { get; set; }

    [DataType(DataType.ImageUrl)]

    public string ImageUrl { get; set; }

    [DataType(DataType.Upload)]
    [NotMapped]
    public HttpPostedFileBase ImageUpload { get; set; }

    public virtual Usuario Usuario { get; set; }

    public virtual Genero Genero { get; set; }
}

}

我的控制器:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "idPerfil,idUsuario,idGenero,descricao,linkMultimidia,fotoPerfil")] Perfil perfil)
    {
        var validImageTypes = new string[]
        {
            "image/gif",
            "image/jpeg",
            "image/pjpeg",
            "image/png"
        };

        if (perfil.ImageUpload == null || perfil.ImageUpload.ContentLength == 0)
        {
            ModelState.AddModelError("ImageUpload", "This field is required");
        }
        else if (!validImageTypes.Contains(perfil.ImageUpload.ContentType))
        {
            ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
        }

            if (ModelState.IsValid)
            {
                if (perfil.ImageUpload != null && perfil.ImageUpload.ContentLength > 0)
                {
                    var uploadDir = "~/Imagens";
                    var imagePath = Path.Combine(Server.MapPath(uploadDir), perfil.ImageUpload.FileName);
                    var imageUrl = Path.Combine(uploadDir, perfil.ImageUpload.FileName);
                    perfil.ImageUpload.SaveAs(imagePath);
                    perfil.ImageUrl = imageUrl;
                }

                    rep.IncluirPerfil(perfil);
                    return RedirectToAction("Index");
            }

        ViewBag.idGenero = new SelectList(db.Generos, "idGenero", "nomeGenero", perfil.idGenero);
        ViewBag.idUsuario = new SelectList(db.Usuarios, "idUsuario", "nome", perfil.idUsuario);
        return View(perfil);
    }

我的创建视图:

    <div class="form-group">
        @using (Html.BeginForm("Create", "PerfilController", FormMethod.Post, new { enctype = "multipart/form-data" }))
            {
             <div class="col-md-10">   
                @Html.LabelFor(model => model.ImageUpload)
              </div>
                 @Html.TextBoxFor(model => model.ImageUpload, new { type = "file" })
            }            
      </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>

我尝试了其他解决方案,但仍然无效...

2 个答案:

答案 0 :(得分:1)

提交按钮必须位于using块内:

<div class="form-group">

    @using (Html.BeginForm("Create", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
    {
        @Html.AntiForgeryToken()
        <div class="col-md-10">
            @Html.LabelFor(model => model.ImageUpload)
        </div>
        @Html.TextBoxFor(model => model.ImageUpload, new {type = "file"})
        <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>

同时将ImageUpload添加到绑定列表:

public ActionResult Create([Bind(Include = "idPerfil,idUsuario,idGenero,descricao,linkMultimidia,fotoPerfil, ImageUpload")] Perfil perfil)

还有一件事,您可以在案件中使用Exclude代替Include

答案 1 :(得分:0)

我解决了!

实体:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "idPerfil,idUsuario,idGenero,descricao,linkMultimidia,photoPath")] Perfil perfil)
{
    string filename = perfil.photoPath;

    var uploadDir = "~/Imagens";
    var imagePath = Path.Combine(Server.MapPath(uploadDir), filename);
    var imageUrl = Path.Combine(uploadDir, filename);
    perfil.photoPath = imageUrl;

    if (ModelState.IsValid)
    {
        rep.IncluirPerfil(perfil);
        return RedirectToAction("Index");
    }

    ViewBag.idGenero = new SelectList(db.Generos, "idGenero", "nomeGenero", perfil.idGenero);
    ViewBag.idUsuario = new SelectList(db.Usuarios, "idUsuario", "nome", perfil.idUsuario);
    return View(perfil);
}

控制器:

<div class="form-group">
    @Html.LabelFor(model => model.photoPath, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.TextBoxFor(model => model.photoPath, new { type = "file" })
        @Html.ValidationMessageFor(model => model.photoPath)
    </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>

创建视图:

<?php if(!is_page( 'STATE FINANCIAL AID' ) { ?>
<div id="top-navigation">
    <?php get_search_form(); ?>
</div>
<?php } ?>