0

Problem Statement: I want to change the display name of labels(@Html.LabelFor) in Razor view of MVC based on the display names which i get from db.

I have added the dropdown list of languages in the _Layout.cshtml

 <li>@Html.Action("Index", "LanguageDropdown", new { languageid = Request["languageId"] })</li>

I have created one partial view for drop down:

@model ALCMS.Web.Models.Master_or_Configuration.LanguageDropdownModel
    <script type="text/javascript">
        function GetLanguage() {
            var languageId = $('#LanguageId').val();
            var Url = "@Url.Content("~/MasterConfigGeneral/GetLanguage")";
            $.ajax({
                url: Url,
                dataType: 'json',
                data: { LanguageId: languageId },
                success: function (data) {
                }
            });
        }
        </script>
    <div style="display:inline-block">

   @Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })
        </div>

Partial View Controller:

public ActionResult Index(string languageId)
    {
        //return View();

        var languages = dbEntity.LookupLanguages;
        var model = new LanguageDropdownModel
        {
            LanguageID = languageId,
            Languages = languages.ToList().Select(l => new SelectListItem
            {
                Value = Convert.ToString(l.LanguageID),
                Text = l.Name
            })
        };
        return PartialView(model);
    }

In Controller Json Result method:

   public JsonResult GetLanguage(int languageID)
        {
            JsonResult jsResult = new JsonResult();
            objdbGlobalTenant.ddlLanguage = (from lsr in dbEntity.LocaleStringResources
                                             where lsr.LanguageID == languageID

                                             select new SelectListItem()
                                             {
                                                 Text = lsr.ResourceValue,
                                                 Value = lsr.ResourceName

                                             }).Distinct().ToList<SelectListItem>();

            //ViewBag.Language = objdbGlobalTenant.ddlLanguage;
            jsResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return jsResult;
        }

Now everything is working fine.I'm able to get the selected langaugeID in Json Result method in Controller based on the change event of Language dropdown. Based on this Language ID i'm getting display names(ResourceValue) which i need to apply for the particular view.

Problems:

  • 1>After getting the display names from db how to change display names of particular view when language change event triggers.?? For ex:Currently i'm seeing the Create.CSHTML. Now if i change the language dropdown it should trigger Json Event in controller and after getting values it should apply the values on the view which it got from db.

Note: Dropdown is in Layout.cshtml(like master in .aspx)

  • 2>Drop-down which i placed in Layout.cshtml is getting refreshed every time new view is loaded which inherits(layout.cshtml).How to make the controller to retain it's state during postback??

  • 3>How to get the selected drop-down item from the layout in multiple
    Controllers,to change the display name in each view based on the langaugeid of dropdown in layout

How to do this??If i'm doing wrong suggest me some other ways...

Vishal I P
  • 2,005
  • 4
  • 24
  • 41

1 Answers1

0

Below are the suggestions :

Issue 1 : You may keep one attribute in each label which identifies them uniquely.

Your HTML should render like following

<!-- For English -->
<label label-unique-name="Name">Name</label>
<label label-unique-name="Surname">Surname</label>

<!-- For French -->
<label label-unique-name="Name">nom</label>
<label label-unique-name="Surname">nom de famille</label>

<!-- For Spanish -->
<label label-unique-name="Name">nombre</label>  
<label label-unique-name="Surname">apellido</label>

Here label-unique-name is your attribute, which will remain fixed for each language. Now when you change the language from dropdown you will bring the values like below.

<!-- For English -->
<label-unique-name:"Name",label-value:"Name">;<label-unique-name:"Surname",label-value:"Surname">

<!-- For French -->
<label-unique-name:"Name",label-value:"nom">;<label-unique-name:"Surname",label-value:"nom de famille">

<!-- For English -->
<label-unique-name:"Name",label-value:"nombre">;<label-unique-name:"Surname",label-value:"apellido">

Please note : this is for understanding only, it's not a JSON.

Now using jQuery go through each label and replace the label's value. Hope it'll help you.

Issue 2 :

You can save the selected language's value in session, and generate your dropdown accordingly.

@Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), !string.isNullorEmpty(HttpContext.Current.Sessions["Language"]) ? HttpContext.Current.Sessions["Language"] : "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })
IT ppl
  • 2,626
  • 1
  • 39
  • 56
  • For your second answer where we need to set value for HttpContext.Current.Session["Language"]? – Vishal I P Mar 12 '14 at 10:11
  • You need to set it when your drop down's value is changed. In your case you can set it int GetLanguage() function. Please note while user logs out don't forgot to clear the session. Plus session will hold the value for around 20 minutes by default. You can change this value in web.config file. – IT ppl Mar 12 '14 at 10:17
  • !string.IsNullOrEmpty(HttpContext.Current.Session["Language"].ToString()) ? HttpContext.Current.Session["Language"].ToString() : "Select Language" is giving Object reference not set to an instance of an object exception(null exception) – Vishal I P Mar 12 '14 at 10:28
  • Is session's value stored properly ? – IT ppl Mar 12 '14 at 10:33
  • As suggested by you i'm setting Session["Language"]=languageID in GetLanguage Method,which will triggered on change event.But before that i will be filling dropdown from the action result method defined in the controller of partial view for dropdown.After getting the languages for the dropdown in view i'm getting error. – Vishal I P Mar 12 '14 at 10:40
  • I have edited my question.I have added Partial View Controller Action Result method for your reference. – Vishal I P Mar 12 '14 at 10:46
  • Now I'm able to get the session value in drop-down by just using @Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text",Session["LanguageId"]),"Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" }) in Dropdown partial view and setting Session["LanguageId"] in Getlanguage Controller. For the 1st question I want to assign JsonResult to ViewBag.Language and want to access this in views.I'm able to assign but when i try to access it in view it is returning null.Viewbag is losing its contents why? which u can see in the Json method for reference – Vishal I P Mar 12 '14 at 11:55
  • Vishal, Can you please check in Browser tools whether getLanguage() method is returning data properly ? Tools like FireBug in FireFox or Fiddler etc. – IT ppl Mar 12 '14 at 13:34
  • Vishal do not return the result in ViewBag. You will get those content in your ajax call, i.e. GetLanugage() function written in script block of your partial view. Just put alert in success: function (data) {alert(data)} and do let me know what it alerts. – IT ppl Mar 12 '14 at 13:37
  • IT ppl, I'm getting values from GetLanguage(). I'm able to access those values in the drop-down partial view. But i want to access these values in some other views. How can we access selected drop-down item in the layout in multiple views? – Vishal I P Mar 12 '14 at 13:52
  • I think you are not clear about your question. Please correct me if I didn't get your point. According to your initial question you were not sure about the mechanism to handle I18N for the labels so I suggested the solution to handle using attribute thing in your labels. Does it solve your original issue#1 ? In your last comment you mentioned something else, like accessing in other/multiple views etc. So please elaborate it. Is it issue#3 ? or it is disturbing to achieve the solution to your first issue. Please make sure and edit your question accordingly. – IT ppl Mar 12 '14 at 14:03
  • Your Index() method is returning the list of languages that you are binding to the dropdown. While your GetLanguage() method in JavaScript part calls the GetLanguage() method of controller. Your Controller's GetLanguage() method receives the LanguageId as argument and retruns the contents (labels) according that language. Am I right here ? – IT ppl Mar 12 '14 at 14:04
  • Yes. You are correct.Sorry,I have updated my question. Whatever you suggested for both issue #1 and #2 solved my problem.Now this is issue #3,where i want to access the selected drop-down item from layout in different view(While performing CRUD operations in each view). – Vishal I P Mar 12 '14 at 14:14
  • Vishal if your earlier questions are resolved than close this question by marking this one as answer. Create a new question with your third question and put this question as reference. Please do that so it will be helpful to some one in future. – IT ppl Mar 12 '14 at 14:19
  • I have created new question for my third issue.Please suggest some answers. [link for new question](http://stackoverflow.com/questions/22354687/in-mvc-razor-how-to-access-selected-drop-down-value-from-layout-in-multiple-view) – Vishal I P Mar 12 '14 at 14:49