我已经创建了一个表单来上传有关广告的详细信息,我需要上传一张图片。在我所有的努力结束时,我仍然在数据库中看到图片列为 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
}