如何在MVC 4中保存带有图像的模型

时间:2015-03-26 08:31:12

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

我编写了一个"产品创建"将产品完美保存到数据库的页面...产品具有ID,CODE,NAME属性。现在我还需要添加Image。

我的旧代码在

之下
[HttpPost]
public ActionResult ProductsCreate(ProductDetailViewModel prod_)
{
    if (ModelState.IsValid)
    {
       db.AY_PRODUCTS.Add(prod_.product);
       db.SaveChanges();
    }      
}

如何更改视图和控制器以使用图像保存模型?

3 个答案:

答案 0 :(得分:4)

将属性HttpPostedFileBase添加到模型中。在视图中使用它来发布图像。

public HttpPostedFileBase YourFile { get; set; }

在您的操作中,将此图像保存到您的位置。

在您的视图中:记住表单中的enctype = "multipart/form-data"

<input name="YourFile" id="YourFile" type="file" accept="image/jpeg, image/png,image/jpg" value="">

提示:也许这不是您的问题所在。您应该将操作命名为&#34;创建&#34;。如果我没错,你有ProductController,对吧?所以你只需要将其命名为Create,不需要&#34; ProductsCreate&#34;。

答案 1 :(得分:2)

在模型中添加

[Display(Name = "Upload File")]
[DataType(DataType.Upload)]
public HttpPostedFileBase Image { get; set; }

在您的视图中,允许您的表单通过添加此enctype = "multipart/form-data"

来发布文件
@using (@Html.BeginForm("ActionName","ControllerName",FormMethod.Post,new { enctype = "multipart/form-data" }))

答案 2 :(得分:0)

//在视图中

@using (Html.BeginForm("Create", "Banner", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="editor-label">
    @Html.LabelFor(model => model.ImagePath)
</div>
<div class="editor-field">
    <input id="File1" name="File1" type="file" />
    @Html.ValidationMessageFor(model => model.ImagePath)
</div>
}

//在控制器中

[HttpPost]
    public ActionResult Create(tblBanner tblbanner)
    {
        if (ModelState.IsValid)
        {
            if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
            {
                tblbanner.ImagePath = clsUploadFile.uploadFile(Request.Files[0], "/Content/BannerImages/");
            }

            db.tblBanners.AddObject(tblbanner);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(tblbanner);
    }

// clsUploadFile defination是

public static class clsUploadFile
{
    public static string uploadFile(HttpPostedFileBase file, string UploadPath)
    {
        string imgPath = null;
        //var fileName = DateTime.Now.ToString();
        //fileName = fileName.Replace(" ", "_");
        //fileName = fileName.Replace("/", "_");
        //fileName = fileName.Replace(":", "_");
        string fileName = System.IO.Path.GetRandomFileName();
        fileName = fileName.Replace(".", "");
        var ext = System.IO.Path.GetExtension(file.FileName);
        fileName += ext;

        System.IO.DirectoryInfo dr = new System.IO.DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~" + UploadPath));
        System.IO.FileInfo[] files = dr.GetFiles();
        for(;true;)
        {
            if (!files.Where(o => o.Name.Equals(fileName)).Any())
                break;
            else
            {
                fileName = System.IO.Path.GetRandomFileName();
                fileName = fileName.Replace(".", "");
                fileName += ext;
            }
        }
        var path = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~" + UploadPath), fileName);
        file.SaveAs(path);
        imgPath = UploadPath + fileName;
        return imgPath;
    }

    public static bool DeleteFile(string path)
    {
        System.IO.FileInfo file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(path));
        if (file.Exists)
        {
            file.Delete();
            return true;
        }
        else
            return false;
    }
}