【发布时间】:2018-04-30 06:33:41
【问题描述】:
有一个我想上传图片的应用。我为此使用字节数组。
图像是必需的,但是当我将该注释放在变量上并尝试创建图像时,它会在应该有图像时给我错误消息。它还返回模型无效。
当我删除必需项时,它可以工作,但也可以设置为 null,这是我不想要的。
关于 Stack Overflow 的话题似乎并不多。
这是我的模型
[Key]
public int InvoiceId { get; set; }
[Required(ErrorMessage = "Company is required")]
public string Company { get; set; }
[Required(ErrorMessage = "Description is required")]
public string Description { get; set; }
[Required(ErrorMessage = "Amount is required")]
public decimal Amount { get; set; }
[Required(ErrorMessage = "Picture of Invoice Required")]
public byte[] PictureOfInvoice { get; set; }
还有我的控制器:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "Parish Admin, Priest, Administrator")]
public ActionResult Create([Bind(Include = "InvoiceId,Company,Description,Amount,PictureOfInvoice,DateReceived,ChurchId")] Invoice invoice,HttpPostedFileBase File)
{
if (ModelState.IsValid)
{
if (File != null && File.ContentLength > 0)
{
invoice.PictureOfInvoice = new byte[File.ContentLength];
File.InputStream.Read(invoice.PictureOfInvoice, 0, File.ContentLength);
}
else
{
TempData["Error"] = "Upload an Image";
}
db.Invoices.Add(invoice);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", invoice.ChurchId);
return View(invoice);
}
我的观点,以防万一它在那里:
<h2>Add New Invoice</h2>
@if (TempData["Error"] != null)
{
<div style="color:red">@TempData["Error"]</div>
}
@using (Html.BeginForm("Create", "Invoices", FormMethod.Post, new { @class = "form-horizontal", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary()
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Company, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Company, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
@Html.ValidationMessageFor(model => model.Company, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Amount, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Amount,new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
@Html.ValidationMessageFor(model => model.Amount, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.DateReceived, "DateRecieved", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.DateReceived, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
@Html.ValidationMessageFor(model => model.DateReceived, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBoxFor(model => model.Description, new { htmlAttributes = new { @class = "form-control", style = "width:20em;" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PictureOfInvoice, "Picture of Invoice", htmlAttributes: new { @class = "control-label col-md-2"})
<div class="col-md-10">
<input type="file" name="File" id="File" style="width: 50%;" />
@Html.ValidationMessageFor(model => model.PictureOfInvoice, "", new { @class = "text-danger" })
<output id="list"></output>
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ChurchId, "Church Name", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ChurchId", null, htmlAttributes: new { @class = "form-control", style = "width:20em;" })
@Html.ValidationMessageFor(model => model.ChurchId, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
<u>
@Html.ActionLink("Back to List", "Index")
</u>
</div>
<script src="~/Scripts/jquery.datetimepicker.js"></script>
<script>
$('#DateReceived').datetimepicker({
format: 'd/m/Y',
weeks: true,
disableWeekDays: [0, 1, 3, 4, 5, 6],
timepicker: false,
inline: false
});
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('File').addEventListener('change', handleFileSelect, false);
</script>
【问题讨论】:
-
没有属性会改变您可以将
array属性设置为null的事实。也许MinLength会更好地为您的验证工作? stackoverflow.com/questions/13361500/… -
@juharr 没有为我做任何事情,甚至没有提供错误消息。我太绝望了,我愿意为此放弃我所有的代表大声笑
-
在您看来,
PictureOfInvoice有一个 标签,PictureOfInvoice有一个验证消息,但我不知道如何您希望<input type="file">与PictureOfInvoice绑定到该属性? -
@Damien_The_Unbeliever 我明白你的意思。但是当我没有所需的部分时它确实有效
-
您的编辑数据,因此请始终使用视图模型 - 它将包含一个属性
HttpPostedFileBase将文件绑定到,但它不包含byte[]属性(请参阅 What is ViewModel in MVC?)
标签: c# asp.net-mvc