0

我已经创建了一个表单来上传有关广告的详细信息,我需要上传一张图片。在我所有的努力结束时,我仍然在数据库中看到图片列为 NULL。我该如何解决这个问题?请注意我是初学者。

视图代码

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

    <div class="editor-label">
        @Html.LabelFor(model => model.Title)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Title)
        @Html.ValidationMessageFor(model => model.Title)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.OwnerID)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.OwnerID)
        @Html.ValidationMessageFor(model => model.OwnerID)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Date)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Date)
        @Html.ValidationMessageFor(model => model.Date)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Category)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.Category,(SelectList)ViewBag.CategoryList)
        @Html.ValidationMessageFor(model => model.Category)
    </div>

    **<div class="editor-label">
        @Html.LabelFor(model => model.Image)
    </div>
    <div class="editor-field">
        <input type="file" id="MyFile" runat="server" />
        @Html.ValidationMessageFor(model => model.Image)
    </div>**

    <div class="editor-label">
        @Html.LabelFor(model => model.Description)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Description)
        @Html.ValidationMessageFor(model => model.Description)
    </div>


    <p>
        <input type="submit" value="Post"  />
    </p>
</fieldset>


 }

表格如下所示 在此处输入图像描述

在我的模型中,我使用“byte []”类型作为 Image 属性。在 sql 数据库中,我使用 Varbinary(max) 类型作为图像列。

数据库表中的代码

CREATE TABLE [dbo].[Advertisements] (
[ID]          INT             IDENTITY (1, 1) NOT NULL,
[Title]       NVARCHAR (100)  NOT NULL,
[OwnerID]     INT             NOT NULL,
[Date]        DATETIME        NOT NULL,
[Category]    NVARCHAR (MAX)  NOT NULL,
[Image]       VARBINARY (MAX) NULL,
[Description] NVARCHAR (200)  NOT NULL,
CONSTRAINT [PK_dbo.Advertisements] PRIMARY KEY CLUSTERED ([ID] ASC)


  );

控制器动作

[HttpPost]
[Authorize]
public ActionResult Create([Bind(Exclude = "ID")]Models.Advertisement advertisement) //submits the result
{

    if (ModelState.IsValid)
    {
        var db = new AdvertisementDataContext();
        db.Advertisements.Add(advertisement);
        db.SaveChanges(); //saved to the database

        return RedirectToAction("Index");
    }

    return Create(); // if there was an error show the form again

}
4

1 回答 1

0

使用 HttpPostedFileBase 将您的文件作为参数发送到控制器 ala: MVC 3 文件上传和模型绑定

那么您需要将该参数转换为字节数组并像您正在做的那样保存它(抱歉,手机上会尝试尽快编辑)

于 2013-10-07T00:34:11.123 回答