【问题标题】:Asp.net - WHY Page is reloading after Ajax call?Asp.net - 为什么页面在 Ajax 调用后重新加载?
【发布时间】:2018-07-21 08:50:45
【问题描述】:

我正在从窗体中的画布中挑选图像。但是 Button 在表单之外。我的图像完全按预期保存,但剩下的问题是 PAGE RELOAD。

单击 BUTTON 时调用 Ajax 以保存画布中的图像:

$("#upload").click(function () {
    var image = document.getElementById("ModelStudedntImageDP").toDataURL("image/png");
    image = image.replace('data:image/png;base64,', '');
    $.ajax({
        type: 'POST',
        url: "../../Admin/UploadImage",
        data: '{ "imageData" : "' + image + '" }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert(msg);
        }
    });
});           

按钮调用:

<button type="button" class="btn btn-primary" id="upload">Test</button>

控制器保存图片的方法:

public void UploadImage(string imageData)
{
    string filePath = Server.MapPath(Url.Content("~/Content/Images/Teacher/"));

    string fileNameWitPath = filePath + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "- ").Replace(":", "") + ".png";
    using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            byte[] data = Convert.FromBase64String(imageData);
            bw.Write(data);
            bw.Close();
        }
    }
}

【问题讨论】:

  • 控制器方法是什么样子的,你也可以粘贴一下吗?
  • 如果您的按钮在表单中,则默认行为是提交该表单,ajax post 是额外提交。如果是这种情况,您需要.preventDefault()
  • @RistoM 我的问题已更新。
  • @Jasen 按钮的 type="button" 所以它在表单中什么都不做。
  • 您显示的代码不会导致页面重新加载

标签: jquery html ajax asp.net-mvc


【解决方案1】:
public JsonResult UploadImage(string imageData)
{
    string filePath = Server.MapPath(Url.Content("~/Content/Images/Teacher/"));

    string fileNameWitPath = filePath + DateTime.Now.ToString().Replace("/", "-").Replace(" ", "- ").Replace(":", "") + ".png";
    using (FileStream fs = new FileStream(fileNameWitPath, FileMode.Create))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            byte[] data = Convert.FromBase64String(imageData);
            bw.Write(data);
            bw.Close();
        }
    }
    return Json(new { success = true, message = "Success" });
}

【讨论】:

  • 这和问题有什么关系(从void改成JsonResult与页面重载无关)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 2021-05-02
  • 2011-12-14
  • 2017-03-16
相关资源
最近更新 更多