0

我已经开始使用 MVC4 + EF 并面临图像上传问题:我想将图像路径保存到 DB,但实际文件~/App_Data/

我需要将一个“ HttpPostedFileBase”和我的自定义“ Image”对象传递给“ Create”控制器。我创建了一个类“ ImageUpload”来传递两个对象。

Image”类:

public class Image
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Path { get; set; }
    public int DepartmentId { get; set; }
}

“图像上传”类:

public class ImageUpload
{
    public Image image { get; set; }
    public HttpPostedFileBase file { get; set; }
}

看法:

@model MvcBannikov.Models.ImageUpload

    @using (Html.BeginForm("Create", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)

        <fieldset>
            <legend>New Photo</legend>

            <div class="editor-label">
                <p>Name:</p>
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.image.Name)
                @Html.ValidationMessageFor(model => model.image.Name)
            </div>

            <div class="editor-label">
                <p>Path:</p>
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.file, new { type = "file" })
                @Html.ValidationMessageFor(model => model.file)
            </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }

Create”方法:

[HttpPost]
public ActionResult Create(ImageUpload image)
{
     ......................
}

问题是ImageUpload对象是NULL:(((

我需要一个文件和 Image 类的原因是 Image 类有一个部门 ID - 我需要那个id

也许您知道另一种解决方案,如何将 aDepartmentId与文件一起传递?

谢谢你的帮助

4

2 回答 2

0

试试这个,只需将您的控制器更改为仅使用您的Image模型并从您的Request对象中获取您的文件

控制器 :

[HttpPost]
public ActionResult Create(Image image)
{
     HttpPostedFileBase myFile = Request.Files["file"];
     ......................
}

没有检查代码,但我记得做过一次。

于 2013-10-09T13:13:59.103 回答
0

再创建一个额外的层,使其成为您的 ViewModel。代替此类设置您需要处理的所有字段,例如:图像类等。并将此 ViewModel 作为您的 MVC 的“模型”分配给您的视图

PS这个解决方案只让您了解如何一次使用多个模型。但是它不包括您的模型的正确性

于 2013-10-09T13:00:07.887 回答