我要做的是让用户在叠加层中上传图片。选择图像后,会添加一个带有图片名称的新行。这是我的代码:
我的叠加HTML:
@model List<GUI.Models.PictureUploadModel>
@using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data", @class = "overlay-form" }))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-md-5">
<h3>File</h3>
</div>
<div class="col-md-5">
<h3>Name</h3>
</div>
<div class="col-md-2 text-center" style="margin-top: 20px;">
<label for="picture-upload">
<i class="fa fa-2x fa-upload" aria-hidden="true"></i>
</label>
<input id="picture-upload" name="ImageUpload" type="file" accept="image/*"/>
</div>
</div>
<div id="image-rows">
@for (int i = 0; i < Model.Count; ++i)
{
@Html.Partial("~/Views/EditorTemplates/UploadRow.cshtml", Model[i])
}
</div>
<div class="text-center margin-top-20">
<button class="btn btn-outline" type="submit"><span>Save</span></button>
</div>
}
此部分视图是在索引视图中添加的叠加层,并使用#pictures-btn打开:
@model GUI.Models.StructureGeneratorModel
<div class="structure-description-container container">
<div class="col-md-8">
@Html.TextAreaFor(m=>m.Description, 10, 60, new { @class = "textarea"})
</div>
<div class="col-md-4">
<div class="btn-container">
<button id="pictures-btn" class="popup-trigger btn btn-active uppercase">Pictures</button>
</div>
</div>
</div>
@Html.Partial("~/Views/EditorTemplates/UploadOverlay.cshtml", Model)
部分视图包含一个带有图像名称的行:
UploadRow.cshtml
@model GUI.Models.PictureUploadModel
@Html.HiddenFor(m=>m.ImageData)
<div class="col-md-5">
<label for="FileName" id="FileName">@Model.FileName</label>
</div>
<div class="col-md-5">
@Html.TextBoxFor(m => m.Name)
</div>
现在,当用户点击#picture-upload btn时,他可以添加图片。然后我敲了一下ajax帖子UploadImageRow。
[HttpPost]
public ActionResult UploadImageRow()
{
try
{
HttpPostedFileBase image = Request.Files[0];
var callModel = new PictureUploadModel(image.FileName, image.FileName);
callModel.ImageData = image;
return PartialView("~/Views/EditorTemplates/UploadRow.cshtml", callModel);
}
catch (Exception e)
{
}
return PartialView("~/Views/EditorTemplates/UploadRow.cshtml", new PictureUploadModel());
}
我追加的返回部分视图使用javascript进行div#image-rows。直到现在一切正常。该行已添加。但是这个新行没有绑定到我的模型。我错过了什么?
我的 PictureUploadModel 如下所示:
public class PictureUploadModel
{
//public int ID { get; set; }
public string Name { get; set; }
public string FileName { get; set; }
public HttpPostedFileBase ImageData { get; set; }
}
当我保存叠加层(提交表单)时,信息图像行消失,当我关闭它(不提交表单)时,信息图像行仍然在我的叠加层中,但它仍然没有绑定到我的模型。