我有一个帐户页面,用户可以在其中更新他/她的个人资料图片。我使用 Amazon S3 来存储图像,因此在成功上传后,我返回图像 URL 以填充图像 src
和带有 URL 值的 TextBoxFor
。但是,当我提交表单时,提交到我的 POST 的模型仍然包含桌面文件名,而不是 Amazon S3 URL。
这是我的 ajax 调用(成功后)填充 img
字段和 TextBoxFor
字段:
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Account/UploadProfImageToS3Return",
data: formdata,
processData: false,
contentType: false,
success: function (data) {
$("#profile-image").attr("src", data);
$("#profImage").attr("value", data);
},
error: function (jqXHR, textStatus, errorThrown) {
//TODO: Indicate Error
console.log(jqXHR);
}
});
});
这是我的Html.BeginForm
:
@using (Html.BeginForm("General", "Account", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
<img id="profile-image" src="@Model.Artist.ImageURL" alt="Profile Image" />
@Html.TextBoxFor(m => m.Artist.ImageURL, new { @name = "profImage", @id = "profImage", @type = "file" })
<div class="form-group">
<input type="submit" value="Save" class="btn btn-default btn-form" />
</div>
}
将文件添加到 @Html.TextBoxFor(m => m.Artist.ImageURL, new { @name = "profImage", @id = "profImage", @type = "file"} )
名为:20507471_10214.jpg
,文件上传后,TextboxFor
的值现在为 https://s3.amazonaws.com/unlink/profile-picture/xxxxxxx.jpg
(因为我在AJAX成功后更新了字段)
但是当我在此处设置断点时:
[HttpPost]
public ActionResult General(Artist artist)
我检查了artist.ImageURL
它仍然等于20507471_10214.jpg
我可以做什么来解决这个问题?
编辑,图像证明每个属性的 value/src 属性设置正确:
最佳答案
好吧,所以解决方法是不使用:
@Html.TextBoxFor(m => m.Artist.ImageURL, new { @name = "profImage", @id = "profImage", @type = "file"})
并使用类似这样的东西,使用隐藏的表单元素来绑定(bind)提交上的值...奇数,但有效:
<input name="profImage" id="profImage" type="file" />
@Html.HiddenFor(m => m.Artist.ImageURL)
在 AJAX 成功后,我将 S3 URL 值分配给隐藏表单:
$("#Artist_ImageURL").attr("value", data);
关于jquery - 使用 jQuery 设置 Html.TextBoxFor 值不会反射(reflect)在模型 POST 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51257591/