一.创建项目
首先我们来创建一个ASP.NET Application
选择时尚时尚最时尚的MVC,为了使演示的Demo更简单,这里选择无身份验证
二.创建相关类
项目需要引入之前两个类AdmAccessToken和AdmAuthentication以便获取访问令牌,并添加一个名为Translator的控制器方便处理相关的业务
注意需要添加程序集System.Runtime.Serialization
添加一个Language_Codes
public class Language_Codes { public int Id { get; set; } public string code { get; set; } public string Name { get; set; } }
三.创建数据库上下文类
首先我们需要引入Entity Framework框架,这里使用的是Nuget包管理
添加类CodeEntity,并且让它继承DbContext
public CodeEntity() : base("DefaultConnection") { } public DbSet<Language_Codes> Language_Code{get;set;}}
接下来修改webconfig
<connectionStrings> <add name="DefaultConnection" connectionString="server=.;database=LanguageCode;uid=sa;pwd=" providerName="System.Data.SqlClient" /> </connectionStrings>
在 TranslatorController中添加
CodeEntity dbcontext = new CodeEntity();
这要我们可以获取语言对应的代码了
四.搭建界面
1.修改Index方法
public ActionResult Index() { List<Language_Codes> list= dbcontext.Language_Code.ToList(); return View(list); }
给TranslatorController的Index添加视图
@model IEnumerable<Translator.Models.Language_Codes> @{ ViewBag.Title = "Index"; } <table class ="table table-striped"> <tr> <td> <label>要翻译的文本</label> <textarea id="text" class="form-control" rows="5"></textarea> </td> <td> 将 <select id="from" class="form-control"> <option value="1">请选择</option> @foreach (var item in Model) { <option id="@item.Id" value="@item.code">@item.Name</option> } </select> 翻译成 <select id="to" class="form-control"> <option value="1">请选择</option> </select> <button id="submit" class="btn btn-default">翻译</button> </td> <td> <label>翻译的文本</label> <textarea id="transtext" class="form-control" rows="5"></textarea> </td> </tr> </table>在layout.cshtml中添加
1 <div class="navbar-collapse collapse"> 2 <ul class="nav navbar-nav"> 3 <li>@Html.ActionLink("主页", "Index", "Home")</li> 4 <li>@Html.ActionLink("关于", "About", "Home")</li> 5 <li>@Html.ActionLink("联系方式", "Contact", "Home")</li> 6 <li>@Html.ActionLink("翻译", "Index", "Translator")</li> 7 </ul> 8 </div> 效果如下
五.利用AJAX动态加载数据
1.加载LanguageCode
首先在控制器中添加一个LoadLanguageCode来处理加载语言代码请求
public ActionResult LoadLanguageCode(int id) { List<Language_Codes> list = dbcontext.Language_Code.Where(c=>c.Id!=id).ToList(); return Json(list); }
在Scripts文件夹添加一个translator.js文件,并在视图中添加此文件的引用<script src="~/Scripts/translator.js"></script>给第一个select注册一个事件,每次select中选项更改时我们去加载第二个select的选项document.getElementById("from").onchange=function() { var selectedid = $(":selected","#from").attr("id"); $.ajax( { url: "../Translator/LoadLanguageCode", type: "post", data: { id: selectedid }, success: function (_JsonData) { $(‘#to‘).empty(); for (var i = 0; i < _JsonData.length; i++) { $(‘#to‘).append($(‘<option‘ + ‘ id=‘ + _JsonData[i].Id + ‘ value=‘ + _JsonData[i].code + ‘>‘ + _JsonData[i].Name + ‘</option>‘)); } } }) }2.向microsoft请求服务在TranslatorController添加 Translate方法
[HttpPost] public ActionResult Translate(string from,string to,string text) { AdmAuthentication adm = new AdmAuthentication("zuin", "Ursm3pji3Fcha+70plJFrAbHT/Y00F7vyKdXlWLusmc="); //string text = textBox1.Text; //string from = "zh-CHS";//"zh-CHS" //string to = "en"; string uri = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text=" + System.Web.HttpUtility.UrlEncode(text) + "&from=" + from + "&to=" + to; string authToken = "Bearer" + " " + adm.token.access_token; HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(uri); httpWebRequest.Headers.Add("Authorization", authToken); WebResponse response = null; try { response = httpWebRequest.GetResponse(); using (Stream stream = response.GetResponseStream()) { System.Runtime.Serialization.DataContractSerializer dcs = new System.Runtime.Serialization.DataContractSerializer(Type.GetType("System.String")); string translation = (string)dcs.ReadObject(stream); return Json(translation); } } catch { string code = "fail"; return Json(code); } }给“翻译”按钮注册事件
$(‘#submit‘).click( function () { var formvalue =$("#from").val(); var tovalue = $("#to").val(); var textvalue = $("#text").val(); $.ajax( { url: "../Translator/Translate", type: "post", data: {from: formvalue, to: tovalue, text:textvalue }, success: function (_JsonData) { $(‘#transtext‘).empty(); if (_JsonData==‘fail‘) { alert("失败!,请联系管理员或使用微软必应在线翻译"); } else { document.getElementById("transtext").innerHTML = _JsonData; } } }) } )
好了 现在可以使用服务了
由于业务很复杂,即使网络很好延迟还是很严重,需要优化下
时间: 2024-10-11 00:20:16