我想知道如何根据输入的名称在网页中引用特定的元素/键。
我有一个如下表单,我想将三个图像上传到SQL-Express数据库中:
else if (property.PropertyName == "Image1")
{
<div class="form-group">
<label for="file1">Filename:</label>
<input type="file" name="fileUpload[0]" />
@if (Model.Image1 == null)
{
<div class="form-control-static">No Image</div>
}
else
{
<div> Image</div>
}
</div>
}
else if (property.PropertyName == "Image2")
{
<div class="form-group">
<label for="file2">Filename:</label>
<input type="file" name="fileUpload[1]" />
@if (Model.Image2 == null)
{
<div class="form-control-static">No Image</div>
}
else
{
<div> Image</div>
}
</div>
}
else if (property.PropertyName == "Image3")
{
<div class="form-group">
<label for="file3">Filename:</label>
<input type="file" name="fileUpload[2]" />
@if (Model.Image3 == null)
{
<div class="form-control-static">No Image</div>
}
else
{
<div> Image</div>
}
</div>
}
我的控制器如下:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Client client, IEnumerable<HttpPostedFileBase> fileUpload)
{
if (ModelState.IsValid)
{
if(fileUpload != null)
{
foreach (var file in fileUpload)
{
//if (file.ContentType == "jpg")
//{
if (file.FileName == "fileUpload[0]")
{
client.Image1 = new byte[file.ContentLength];
file.InputStream.Read(client.Image1, 0, file.ContentLength);
}
if (file.FileName == "fileUpload[1]")
{
client.Image2 = new byte[file.ContentLength];
file.InputStream.Read(client.Image2, 0, file.ContentLength);
}
if (file.FileName == "fileUpload[2]")
{
client.Image3 = new byte[file.ContentLength];
file.InputStream.Read(client.Image3, 0, file.ContentLength);
}
//}
}
}
Repo.SaveProduct(client);//this is an interface to save the changes to the database.
return RedirectToAction("Index");
如何映射回Enumerable中的特定变量,我正在使用此文件。文件名==“fileUpload [2]”。我很确定这是错的。我正在尝试引用html标签''。有没有办法做到这一点?
答案 0 :(得分:0)
转换为列表并使用索引
if(fileUpload != null) {
var files = fileUpload.ToList();
for (var index = 0; index < files.Count; index++) {
var file = files[index];
if (index == 0) {
client.Image1 = new byte[file.ContentLength];
file.InputStream.Read(client.Image1, 0, file.ContentLength);
}
if (index == 1) {
client.Image2 = new byte[file.ContentLength];
file.InputStream.Read(client.Image2, 0, file.ContentLength);
}
if (index == 2) {
client.Image3 = new byte[file.ContentLength];
file.InputStream.Read(client.Image3, 0, file.ContentLength);
}
}
}