.Net国际化多语言简单实现

实现思路

    利用xml文档存储项目语言,特定语言使用特定xml。

运行结果




代码

    VS创建简单mvc项目

    修改Home控制器,使用Cookie存储客户端语言信息。

    

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            DataTable dt = new DataTable();
            string languagetype = "";
            string xmlpath = "~/Xml/Language-";
            //读取Cookies
            if (Request.Cookies["lan"] != null)
            {
                languagetype = Request.Cookies["lan"].Value;
            }else
            {
                languagetype = "zh";
            }
            //拼接xml路经
            xmlpath = xmlpath + languagetype + ".xml";
            //获取xml数据并转换为datatable
            dt=XmlHelper.CXmlFileToDataSet(xmlpath).Tables[0];
            ViewBag.dt = dt;
            return View();
        }
        /// <summary>
        /// 更换语言
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SetLanguage(string cookies)
        {
            if (cookies != "")
            {
                if(cookies == "zh")
                {
                    Response.Cookies["lan"].Value = "en";
                }else
                {
                    Response.Cookies["lan"].Value = "zh";
                }
            }
            else
            {
                Response.Cookies["lan"].Value = "en";
            }


            return Json(true);
        }


        
    }
}

    XML转换类 XmlHelper

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Xml;

namespace WebApplication1
{
    public class XmlHelper
    {
        /// <summary>
        /// 读取Xml文件信息,并转换成DataSet对象
        /// </summary>
        /// <remarks>
        /// DataSet ds = new DataSet();
        /// ds = CXmlFileToDataSet("/XML/upload.xml");
        /// </remarks>
        /// <param name="xmlFilePath">Xml文件地址</param>
        /// <returns>DataSet对象</returns>
        public static DataSet CXmlFileToDataSet(string xmlFilePath)
        {
            if (!string.IsNullOrEmpty(xmlFilePath))
            {
                string path = HttpContext.Current.Server.MapPath(xmlFilePath);
                StringReader StrStream = null;
                XmlTextReader Xmlrdr = null;
                try
                {
                    XmlDocument xmldoc = new XmlDocument();
                    //根据地址加载Xml文件
                    xmldoc.Load(path);

                    DataSet ds = new DataSet();
                    //读取文件中的字符流
                    StrStream = new StringReader(xmldoc.InnerXml);
                    //获取StrStream中的数据
                    Xmlrdr = new XmlTextReader(StrStream);
                    //ds获取Xmlrdr中的数据
                    ds.ReadXml(Xmlrdr);
                    return ds;
                }
                catch (Exception e)
                {
                    throw e;
                }
                finally
                {
                    //释放资源
                    if (Xmlrdr != null)
                    {
                        Xmlrdr.Close();
                        StrStream.Close();
                        StrStream.Dispose();
                    }
                }
            }
            else
            {
                return null;
            }
        }

    }
}

    页面 Home/Index

    

@{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>ASP.NET</h1>
    <p class="lead">@ViewBag.dt.Rows[0]["text"].ToString()</p>
    <p><a οnclick="Change()" class="btn btn-primary btn-lg">@ViewBag.dt.Rows[0]["but"].ToString() »</a></p>
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
     function Change()
    {
        var L = Getjslanguage();
        $.ajax({
            type: "post",
            url: "/Home/SetLanguage",
            data: { cookies: getCookie("lan") },
            success: function (data) {
                if (data) {
                    alert(L.tishi);
                    location.reload();
                }
            }
        });
    }


    function getCookie(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return unescape(arr[2]);
        else
            return null;
    }
</script>

    母版页 ——Layout.cshtml

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - 我的 ASP.NET 应用程序</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("应用程序名称", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("主页", "Index", "Home")</li>
                    <li>@Html.ActionLink("关于", "About", "Home")</li>
                    <li>@Html.ActionLink("联系方式", "Contact", "Home")</li>
                </ul>
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - 我的 ASP.NET 应用程序</p>
        </footer>
    </div>

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)
    @{
        string languagetype = "";
        if (Request.Cookies["lan"] != null)
        {
            
            <script src="~/Xml/Jslanguage-@(Request.Cookies["lan"].Value).js"></script>
        }
        else
        {

            <script src="~/Xml/Jslanguage-zh.js"></script>
        }
    }
   
</body>
</html>

    对应的语言xml&语言Js

Language-zh.xml 中文语言包

<?xml version="1.0" encoding="utf-8" ?>
<language>
  <zh>
    <text>ASP.NET 是一个使用HTML、CSS和JavaScript构建大型网站和Web应用程序的免费Web框架。</text>
    <but>更换</but>
  </zh>
</language>

Language-en.xml 英文语言包

<?xml version="1.0" encoding="utf-8" ?>
<language>
  <zh>
    <text>ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</text>
    <but>Replace</but>
  </zh>
</language>

Jslanguage-zh.js 中文语言js

function Getjslanguage() {
    var L = {
        tishi:"成功!"
    };
    return L;
}

Jslanguage-en.js 英文语言js

function Getjslanguage() {
    var L = {
        tishi: "Success!"
    };
    return L;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

QFN-齐

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

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

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

打赏作者

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

抵扣说明:

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

余额充值