Ajax表单提交

Ajax表单提交

1.post

1.服务器端代码:

[HttpGet]
public ActionResult UserP()
{
    return View();
}
[HttpPost]
public ActionResult UserP(string UserName,string UserPwd)
{
    return Content("用户名" + UserName + "密码" + UserPwd);
}

2.客户端表单代码:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>UserP</title>
</head>
<body>
<form id="fmUserP">
    用户名:<input type="text" name="UserName" id="Name" />
    <br />
    密  码:<input type="text" name="UserPwd" id="Pwd" />
    <br />
    <input type="button" value="保存" id="BtnSave" onclick="saveUser()" />
</form>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
    function saveUser() {
        var fd = $("#fmUserP").serialize();
        $.post("/Home/UserP", fd, function (res) {
            alert(res);
        },'text');
    }
</script>
</body>
</html>

2.Ajax

1.服务器端代码:

public ActionResult CreateUser()
{
    return View();
}
[HttpPost]
public ActionResult CreateUser(string un, HttpPostedFileBase up)
{
   var fileName = Path.Combine(Request.MapPath("~/Content"), Path.GetFileName(up.FileName));
   try
   {
       up.SaveAs(fileName);
       String d = String.Format("用户【{0}】的照片已经保存成功", un);
       return Json(new
       {
           success = true,
           message = d,
           remark = "/Content/" + Path.GetFileName(up.FileName)
       });
   }
   catch (Exception ex)
   {
       return Json(new { success = false, message = ex.Message, remark = "" });
   }
}

2.客户端表单代码:

@{
    Layout = null;
}

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>CreateUser</title>
</head>
<body>
<form id="fmCreateUser">
    姓名:<input type="text" name="un" id="txtUn" />
    <br />
    照片:<input type="file" name="up" id="txtUp" />
    <br />
    <input type="button" value="保存" id="BtnSave" onclick="saveUser()" />
</form>

<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
function saveUser() {
    //写法1
        var fd = new FormData();
        fd.append("un", $("#txtUn").val());
        fd.append("up", $("#txtUp")[0].files[0]);
    //方法2
    //var fd = new FormData(document.getElementById("fmCreateUser"));
    $.ajax({
        url: "/Home/CreateUser",
        type: "POST",
        data: fd,
        success: function (data, textStatus) {
            alert(data.message);
            console.log(data);
        },
        processData: false,//不处理数据
        contentType: false //不设置内容类型
    });
}
</script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

1024节

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值