Xceedas

Xceedas
xceedas

Wednesday, 29 October 2014

How to Create the Multilanguage Application in ASP.Net

Look at the following image:

this is your home page

change language

We can create the Multilanguage application in ASP.NET like the following.

Step 1
Add the Master Page Site1.Master and design the menu and language selection dropdown list like this:
  1. <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="MultilanguageSample.Site1" %>  
  2.    
  3. <!DOCTYPE html>  
  4.    
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <style type="text/css">  
  9.         html {  
  10.             font-family: Tahoma;  
  11.             font-size: 14px;  
  12.             font-style: normal;  
  13.             background-color: Silver;  
  14.         }  
  15.    
  16.         .Content {  
  17.             margin: auto;  
  18.             width: 700px;  
  19.             background-color: white;  
  20.             border: Solid 1px black;  
  21.         }  
  22.         .auto-style1 {  
  23.             width: 100%;  
  24.         }  
  25.     </style>  
  26.     <asp:ContentPlaceHolder ID="head" runat="server">  
  27.     </asp:ContentPlaceHolder>  
  28. </head>  
  29.    
  30. <body>  
  31.     <form id="form1" runat="server">  
  32.         <div class="Content">  
  33.         <br />  
  34.             <table class="auto-style1">  
  35.                 <tr>  
  36.                     <td style="background-color: #339966"> <a href="Default.aspx">  
  37.                 <asp:Label ID="Label1" meta:resourcekey="menuItemDefault" runat="server" Text="Home"></asp:Label>  
  38.             </a></td>  
  39.                     <td style="background-color: #339966; " ><a href="Contact.aspx">  
  40.             <asp:Label ID="Label2" meta:resourcekey="menuItemContact" runat="server" Text="ContactUs"></asp:Label>  
  41.         </a></td>  
  42.                     <td style="background-color: #339966;"><asp:DropDownList ID="DropDownList_Language" runat="server" Height="20px" Width="170px"  
  43.             OnSelectedIndexChanged="DropDownList_Language_SelectedIndexChanged" AutoPostBack="true">  
  44.             <asp:ListItem Value="en-US">English</asp:ListItem>  
  45.             <asp:ListItem Value="sv-SE">Swedish</asp:ListItem>  
  46.         </asp:DropDownList></td>  
  47.                 </tr>  
  48.             </table>  
  49.         <br />  
  50.         <br />  
  51.    
  52.         <div>  
  53.             <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">  
  54.             </asp:ContentPlaceHolder>  
  55.         </div>  
  56.         </div>  
  57.     </form>  
  58. </body>  
  59. </html>  
Step 2
Write the code in the code behind file like this:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.    
  8. namespace MultilanguageSample  
  9. {  
  10.     public partial class Site1 : System.Web.UI.MasterPage  
  11.     {  
  12.          
  13.         protected void Page_Load(object sender, EventArgs e)  
  14.         {  
  15.             if (Session["language"] != null && !IsPostBack)  
  16.             {  
  17.                 DropDownList_Language.ClearSelection();  
  18.                 DropDownList_Language.Items.FindByValue(Session["language"].ToString()).Selected = true;  
  19.             }  
  20.         }  
  21.         protected void DropDownList_Language_SelectedIndexChanged(object sender, EventArgs e)  
  22.         {  
  23.             switch (DropDownList_Language.SelectedValue)  
  24.             {  
  25.                 case "en-US": this.SetMyNewCulture("en-US");  
  26.                     break;  
  27.                 case "sv-SE": this.SetMyNewCulture("sv-SE");  
  28.                     break;  
  29.                 default:  
  30.                     break;  
  31.             }  
  32.             Response.Redirect(Request.Path);  
  33.         }  
  34.    
  35.         private void SetMyNewCulture(string culture)  
  36.         {  
  37.             Session["language"] = culture;  
  38.         }  
  39.     }  
  40. }  
Note: Here you can also store the user language selection in cookies or Local Storage of HTML 5 using JavaScript. This can be used to maintain the user preference language at page Load.

Step 3
Create a “App_LocalResources” folder and add the resources as page wise.

Like Site.master.resx for English and Site1.Master.sv. resx for Swedish. 

Note: Keep the separate resource file for each page for better maintainability.

master page

Step 4
Add this method in the global.asax file:
  1. void Application_AcquireRequestState(object sender, EventArgs e)  
  2. {  
  3.       HttpContext context = HttpContext.Current;  
  4.       if (context.Session["language"] != null)  
  5.       {  
  6.             Thread.CurrentThread.CurrentUICulture = new CultureInfo(context.Session["language"].ToString().Trim());  
  7.             Thread.CurrentThread.CurrentCulture = new CultureInfo(context.Session["language"].ToString().Trim());  
  8.       }  
  9. }  
This is used for getting the current state of the session.

Step 5
Call the resource key on the label like this as page wise.
  1. <asp:Label ID="Label1" meta:resourcekey="menuItemDefault" runat="server" Text="Home"></asp:Label>   
You call also call the resource file in C# like this:
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3. lblMsg.Text = GetLocalResourceObject("lblMsgHome.Text").ToString();  
  4.   
  5. }  
Note: Please let me know if you have any good approach to do this. 

How to Implement Insert, Update, Delete Functionality in Single View of ASP.NET MVC?


employee detail

By default ASP.NET MVC does not support this approach. We have to implement some tricks to achieve this task. 

Step 1
Create the blank application like this:

eisk mvc

empty asp project

Step 2
Create the database table like this:

employee demo in MVC

Step 3
In model layer, create the model using an EF database first approach like this:

navigation property

Step 4
Now create a blank Emp controller like this:

add controller

Step 5
Add a class i.e HttpParamActionAttribute in a solution like this:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Reflection;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.    
  8. namespace EmpDemoInMVC  
  9. {  
  10.     public class HttpParamActionAttribute : ActionNameSelectorAttribute  
  11.     {  
  12.         public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)  
  13.         {  
  14.             if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))  
  15.                 return true;  
  16.    
  17.             var request = controllerContext.RequestContext.HttpContext.Request;  
  18.             return request[methodInfo.Name] != null;  
  19.         }  
  20.     }  
  21. }  
Note: We are writing this class to fire the multiple Submit button events from a single view.

Step 6
Write the Action Method in Controller for Insert/Update/Delete and fetch functionalities like this:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using EmpDemoInMVC.Models;  
  7. using System.Data.Entity;  
  8.    
  9. namespace EmpDemoInMVC.Controllers  
  10. {  
  11.     public class EmpController : Controller  
  12.     {  
  13.    
  14.         EmpEntities db = new EmpEntities();  
  15.           
  16.         //  
  17.         // GET: /Emp/  
  18.         public ActionResult Index(int? id)  
  19.         {  
  20.             ViewBag.Operation = id;  
  21.             ViewBag.Name = db.tblEmps.ToList();  
  22.             tblEmp objEmp = db.tblEmps.Find(id);  
  23.             return View(objEmp);  
  24.         }  
  25.    
  26.         [HttpPost]  
  27.         [HttpParamAction]  
  28.         [ValidateAntiForgeryToken]  
  29.         public ActionResult Create(tblEmp objEmp)   
  30.         {  
  31.             if (ModelState.IsValid)  
  32.             {  
  33.                 db.tblEmps.Add(objEmp);  
  34.                 db.SaveChanges();  
  35.             }  
  36.             return RedirectToAction("Index");  
  37.         }  
  38.    
  39.         [HttpPost]  
  40.         [HttpParamAction]  
  41.         [ValidateAntiForgeryToken]  
  42.         public ActionResult Update(tblEmp objEmp)  
  43.         {  
  44.             if (ModelState.IsValid)  
  45.             {  
  46.                 db.Entry(objEmp).State = EntityState.Modified;  
  47.                 db.SaveChanges();  
  48.             }  
  49.             return RedirectToAction("Index", new { id = 0 });  
  50.         }  
  51.    
  52.         public ActionResult Delete(int id)  
  53.         {  
  54.             tblEmp objEmp = db.tblEmps.Find(id);  
  55.             db.tblEmps.Remove(objEmp);  
  56.             db.SaveChanges();  
  57.             return RedirectToAction("Index", new { id = 0 });  
  58.         }  
  59.     }  
  60. }  
Step 7
Create the Empty View from controller like this:

add view

Step 8
Now write the html code as per as our requirement like this:
  1. @model EmpDemoInMVC.Models.tblEmp  
  2.    
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.    
  7. <h2>Index</h2>  
  8.    
  9. @using (Html.BeginForm())   
  10. {  
  11.     // This is For EmpDetail in Grid  
  12.         <fieldset>  
  13.             <legend><b>Emp Details</b></legend>  
  14.             <table border="1" cellpadding="10">  
  15.                 <tr>  
  16.                     <th>  
  17.                         @Html.DisplayNameFor(model => model.Name)  
  18.                     </th>  
  19.                     <th>  
  20.                         @Html.DisplayNameFor(model => model.Address)  
  21.                     </th>  
  22.                     <th>  
  23.                         @Html.DisplayNameFor(model => model.EmailId)  
  24.                     </th>  
  25.                     <th>  
  26.                         @Html.DisplayNameFor(model => model.MobileNo)  
  27.                     </th>  
  28.                     <th>  
  29.                         @Html.DisplayNameFor(model => model.Country)  
  30.                     </th>  
  31.                     <th>  
  32.                         Action  
  33.                     </th>  
  34.                 </tr>  
  35.    
  36.                 @foreach (var item in (IEnumerable<EmpDemoInMVC.Models.tblEmp>)ViewBag.Name)  
  37.                 {  
  38.                     <tr>  
  39.                         <td>  
  40.                             @Html.DisplayFor(modelItem => item.Name)  
  41.                         </td>  
  42.                         <td>  
  43.                             @Html.DisplayFor(modelItem => item.Address)  
  44.                         </td>  
  45.                         <td>  
  46.                             @Html.DisplayFor(modelItem => item.EmailId)  
  47.                         </td>  
  48.                         <td>  
  49.                             @Html.DisplayFor(modelItem => item.MobileNo)  
  50.                         </td>  
  51.                         <td>  
  52.                             @Html.DisplayFor(modelItem => item.Country)  
  53.                         </td>  
  54.                         <td>  
  55.                             @Html.ActionLink("Edit", "Index", new { id = item.Id }) |  
  56.                             @Html.ActionLink("Delete", "Delete", new { id = item.Id })  
  57.                         </td>  
  58.                     </tr>  
  59.                 }  
  60.    
  61.             </table>  
  62.       </fieldset>  
  63.       
  64.     // This is for the Emp Entry Screen  
  65.     @Html.AntiForgeryToken()  
  66.     <div class="form-horizontal">  
  67.          
  68.         @Html.ValidationSummary(true)  
  69.    
  70.         <fieldset>  
  71.             <legend> <b>Entry Screen</b></legend>  
  72.    
  73.             <div class="form-group">  
  74.                 @Html.LabelFor(model => model.Name, new { @class = "control-label col-md-2" })  
  75.                 <div class="col-md-10">  
  76.                     @Html.EditorFor(model => model.Name)  
  77.                     @Html.ValidationMessageFor(model => model.Name)  
  78.                 </div>  
  79.             </div>  
  80.    
  81.             <div class="form-group">  
  82.                 @Html.LabelFor(model => model.Address, new { @class = "control-label col-md-2" })  
  83.                 <div class="col-md-10">  
  84.                     @Html.EditorFor(model => model.Address)  
  85.                     @Html.ValidationMessageFor(model => model.Address)  
  86.                 </div>  
  87.             </div>  
  88.    
  89.             <div class="form-group">  
  90.                 @Html.LabelFor(model => model.EmailId, new { @class = "control-label col-md-2" })  
  91.                 <div class="col-md-10">  
  92.                     @Html.EditorFor(model => model.EmailId)  
  93.                     @Html.ValidationMessageFor(model => model.EmailId)  
  94.                 </div>  
  95.             </div>  
  96.    
  97.             <div class="form-group">  
  98.                 @Html.LabelFor(model => model.MobileNo, new { @class = "control-label col-md-2" })  
  99.                 <div class="col-md-10">  
  100.                     @Html.EditorFor(model => model.MobileNo)  
  101.                     @Html.ValidationMessageFor(model => model.MobileNo)  
  102.                 </div>  
  103.             </div>  
  104.    
  105.             <div class="form-group">  
  106.                 @Html.LabelFor(model => model.Country, new { @class = "control-label col-md-2" })  
  107.                 <div class="col-md-10">  
  108.                     @Html.EditorFor(model => model.Country)  
  109.                     @Html.ValidationMessageFor(model => model.Country)  
  110.                 </div>  
  111.             </div>  
  112.             <div class="form-group">  
  113.                 <p>  
  114.                     <input type="submit" value="Create" name="Create"  
  115.                            style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:none" : "display:block") />  
  116.                     <input type="submit" value="Update" name="Update"  
  117.                            style=@((ViewBag.Operation != null && Convert.ToInt32(ViewBag.Operation) > 0) ? "display:block" : "display:none") />  
  118.                 </p>  
  119.             </div>  
  120.             </fieldset>  
  121.    
  122. </div>  
  123. }  
Summary
In this article we show that we are using only one view for doing Insert/Update/Delete and Fetch functionality. If you like to implement entry screen similar to ASP.NET style you can use this approach.