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>