1、视图页面
<!DOCTYPE html>
<html>
<head runat="server">
<title>Index2</title>
<script src="/Scripts/jquery-1.4.4。js" type="text/javascript"></script>
<script type="text/javascript">
var login = function () {
var data = { "username": $.trim($("#username").val()), "pwd": $.trim($("#pwd").val()) }
// $.post("/Home/Login", data, function (message) {
// if (message.success) {
// alert(message.msg);
// }
// else {
// alert(message.msg);
// }
// }, "json");
$.ajax({ type: "post", url: "/Home/Login", data: data, success: function (message) {
if (message.Success) {
alert(message.Msg);
}
else {
alert(message.Msg);
}
}, dataType: "json"
});
}
</script>
</head>
<body>
<div id="nav">
<a href="/Home/Index">ajax+Handler</a> <a>ajax+action</a>
</div>
<div>
<h3>
Login</h3>
Username:<input id="username" name="username" type="text" /><br />
Userpass:<input id="pwd" name="pwd" type="password" /><br />
<button type="button" onclick="login()">
Submit</button>
</div>
</body>
</html>
2、控制器
using System.Web.Mvc;
namespace Mvc1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
//
// GET: /Home/Index2
public ActionResult Index2()
{
return View();
}
// Post: /Home/Login
[HttpPost]
public JsonResult Login()
{
string username=Request["username"];
string pwd = Request["pwd"];
message msg = null;
if (username == "rain" && pwd == "m123")
{
msg = new message(true, "Success");
}
else
{
msg = new message(false, "Fail");
}
return Json(msg);
}
}
class message
{
bool success;
string msg;
public message(bool success, string msg)
{
this.success = success;
this.msg = msg;
}
public bool Success
{
get { return success; }
set { success = value; }
}
public string Msg
{
get { return msg; }
set { msg = value; }
}
}
}
参考资料: MVC JsonResult的用法 http://www.studyofnet.com/news/594.html