如何从ASP.NET MVC项目中的输入类型“文件”中获取文件名?

时间:2013-02-28 18:27:31

标签: c# asp.net-mvc entity-framework razor dbcontext

我是ASP.NET的新手,如果有人可以提供帮助,我会非常感激。 我有我的文件输入:

<form action="NewProject.cshtml" method="post" enctype="multipart/form-data">
<fieldset>
  <legend> Upload Image </legend>
  <label for="Image">Image</label>
  <input type="file" name="Image" id ="filename"/>
  <br/>
  <input type="submit" value="Upload" id="Add" />
</fieldset>

上传图片我使用:

@{  WebImage photo = null;
var newFileName = "";
var imagePath = "";

if(IsPost){
    photo = WebImage.GetImageFromRequest();
    if(photo != null){
        newFileName = Guid.NewGuid().ToString() + "_" +
            Path.GetFileName(photo.FileName);
        imagePath = @"Images\" + newFileName;

        photo.Save(@"~\" + imagePath);
//an attempt
       PoleInvestProject.Models.Project project = new PoleInvestProject.Models.Project();
            project.Image = imagePath; //storing in model property Image

        }
    }
}

现在我需要从那里获取图像的路径并将其与我的模型相关联,模型具有属性public string Image { get; set; }。我想通过DBContext context将此文件路径存储在我的数据库中。

  context.Projects.Add(new Project()
            {

                Image = model.Image

            });
            context.SaveChanges();

但是这给了我NULL,我的数据库表中没有Projects。 我究竟做错了什么? 提前谢谢!

1 个答案:

答案 0 :(得分:0)

通过string的值在模型中创建一个新属性,并将其命名为FileName。现在在您的视图中,创建一个具有相同名称的隐藏文件

<input type="hidden" id="FileName" value="" />

为文件输入添加更改句柄

<input type="file" onchange="document.getElementById('FileName').value = this.value;" />

每次更改时,都应使用文件名的值更新隐藏字段。当您进行回发时,模型绑定器将完成剩下的工作,您将在model.FileName中找到该文件的名称

希望这有帮助

相关问题