jquery - 使用 jQuery 设置 Html.TextBoxFor 值不会反射(reflect)在模型 POST 中

标签 jquery asp.net-mvc

我有一个帐户页面,用户可以在其中更新他/她的个人资料图片。我使用 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 属性设置正确:

enter image description here

最佳答案

好吧,所以解决方法是不使用:

@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/

相关文章:

asp.net-mvc - Action 之间的参数传递

c# - 将自签名ssl证书添加到gcp容器化.net核心Web虚拟机实例

asp.net-mvc - 我们可以像部署WebForm网站项目一样通过复制源代码(不编译)来部署asp.net MVC应用程序吗?

jquery - 如何将 jQuery UI 日期选择器初始化为查询字符串中的日期?

Javascript 按钮监听器触发一次?

javascript 表格技巧隐藏和显示点击按钮的除法

javascript - 如何添加 jQuery scrollTop 偏移量?

asp.net-mvc - 多个用户创建用户时修改了 automapper 错误集合

javascript - Asp.net MVC模态弹出窗口确认后关闭

javascript - jquery tablesorter 插件对格式 : 16-Jan-2010 进行排序