【发布时间】:2012-04-25 00:56:53
【问题描述】:
所以我想对我的唱片收藏进行编目。我也想学习一些MVC。所以我决定在 MVC 中建立一个记录编目网站。我就是这样工作的。
我只是在尝试,但不知道如何将多个文件上传到我的 SQLCE 数据库。我对这里的选项持开放态度 - 将图像存储为 BLOBS 或简单地存储为文件名并将图像上传到文件系统。
我的简单模型是这样的:
public class Record
{
[ScaffoldColumn(false)]
public int RecordId { get; set; }
[Required(ErrorMessage = "Artist is required")]
public string Artist { get; set; }
[Required(ErrorMessage = "Title is required")]
public string Title { get; set; }
[DisplayName("Release Date")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime ReleaseDate { get; set; }
[Required(ErrorMessage = "Format is required")]
public string Format { get; set; }
public string Label { get; set; }
[DisplayName("Catalogue Number")]
public string CatalogueNumber { get; set; }
public string Matrix { get; set; }
public string Country { get; set; }
public IEnumerable<HttpPostedFileBase> Images { get; set; }
public string Notes { get; set; }
}
我的观点是:
@model Records.Models.Record
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Record</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Artist)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Artist)
@Html.ValidationMessageFor(model => model.Artist)
</div>
// snipped for brevity
<div class="editor-label">
@Html.LabelFor(model => model.Notes)
</div>
<div class="editor-field">
@Html.TextAreaFor(model => model.Notes)
@Html.ValidationMessageFor(model => model.Notes)
</div>
<div class="editor-field">
<input type="file" name="images" id="image1"/>
<input type="file" name="images" id="image2"/>
<input type="file" name="images" id="image3"/>
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
而我的 Create 方法是:
[HttpPost]
public ActionResult Create(Record record, IEnumerable<HttpPostedFileBase> images)
{
if (ModelState.IsValid)
{
foreach (HttpPostedFileBase image in images)
{
if (image.ContentLength > 0)
{
var fileName = Path.GetFileName(image.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
image.SaveAs(path);
}
}
db.Records.Add(record);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(record);
}
但是,images(我的 Create 方法参数)始终为 null,而 Model.IsValid 始终为 false。
这是为什么?我尝试将我的图片上传输入命名为“image”、“Image”、“image[n]”,并且 images 始终为 0。
我真的不想为此使用任何插件,有没有简单的原生 MVC 方式?我愿意帮助!
提前致谢。
【问题讨论】:
-
您是否有一个 [HttpGet] 最初传回模型的实例?我看到你得到了 [HttpPost] 部分。
-
@Geovani,是的,我确实有一个仅显示视图的 [HttpGet] 方法。
-
在 HTTPGET 中你是返回一个记录实例还是只是正常返回 View();您可以编辑您的问题并发布您的 HTTGET 方法的代码吗?
标签: asp.net-mvc model-binding image-upload