在ASP.NET MVC中json的应用(即JsonResult)

 编号:ylbtech  DotNet100010011

1,博文简介

 本博文提供了两种解决方案。

a)ajax+Handler

b) ajax+ JsonResult

2,a)例子代码

  1, /Views/Home/Index.aspx  提交页面

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title>index</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("/Handlers/Login.ashx", data, function (message) {
            //                if (message.Success) {
            //                    alert(message.Msg);
            //                }
            //                else {
            //                    alert(message.Msg);
            //                }
            //            }, "json");

            $.ajax({ type: "post",url:"/Handlers/Login.ashx", data: data, success: function (message) {
                if (message.Success) {
                    alert(message.Msg);
                }
                else {
                    alert(message.Msg);
                }
            },dataType:"json"
            });
        }
    </script>
</head>
<body>
<div id="nav">
<a>ajax+Handler</a> <a href="/Home/Index2">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, /Handlers/Login.ashx  (处理程序)

using System.Web;

using System.Web.Script.Serialization;  //引用,序列化程序集
namespace Mvc1.Handlers
{
    /// <summary>
    /// Login 的摘要说明
    /// </summary>
    public class Login : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            string username = context.Request["username"];
            string pwd = context.Request["pwd"];

            message msg = null;
            if (username == "rain" && pwd == "m123")
            {
                msg = new message(true, "S");
            }
            else
            {
                msg = new message(false, "F");
            }
            //创建序列化对象
            JavaScriptSerializer jss = new JavaScriptSerializer();

            context.Response.Write(jss.Serialize(msg)); //返回json格式对象
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 提示信息
        /// </summary>
        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; }
            }
        }
    }
}

 

 3,b)例子代码

1, /Views/Home/Index2.aspx

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!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>&nbsp; <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, /Controllers/HomeController.cs

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; }
        }
    }
}

 

warn 作者:ylbtech
出处:http://ylbtech.cnblogs.com/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

最终目标

 代码的国际化标准示例 ylb,tech”,最大程度地规范软件编程开发统一,优质, 高效,易学,为建设软件强国(中国)而努力。

posted on 2012-10-11 10:53  ylbtech  阅读(19918)  评论(0编辑  收藏  举报