Search code examples
c#bootboxresource-files

replace string dynamically in resource file


In my cshtml page i have one bootbox dialog like this

bootbox.dialog({
                  title: "Addresstitle " + ADDRESS + " save",
                  message: "you will be send to " + fromaddress + "for verification dear" + customer,
                  buttons: {
                   success: {
                                label: "Next,
                                className: "btn btn-success",
                                callback: function(){
                                      //some logic
                                }
                            }
                        }
                    });

I will create 2 resource string in resource file one for title and one for message

Addresstitle {0} save
you will be send to {0} for {1} verification dear {2}

How can i set this text in resource file dynamically?


Solution

  • I'm not sure about your project structure but here is the high level idea how to do solve this:

    1. You store your strings to some resource C# class called Resources ($TITLE$, $FORM$ and $CUSTOMER$ are placeholders that will be replaced later in JS):

      • Key: Title Value: Addresstitle $TITLE$ save
      • Key: Message Value: you will be send to $FORM$ for verification dear $CUSTOMER$.
    2. In your Razor page where you prepare the view you can also provide your server side resources as a JS object within your view so that browser/JavaScript can also use them:

    <script>
      var resourceObj = {
          title: '@Resources.Title',
          message: '@Resources.Message'
      }
    </script>
    
    1. Once the view is loaded in the browser, you can use JavaScript to access that JS object and set the dialog title and message:
    bootbox.dialog({
       title: resourceObj.title.replace("$TITLE$", ADDRESS),
       message: resourceObj.message.replace("$FORM$", fromaddress).replace("$CUSTOMER$", customer),
       buttons: {
           success: {
               label: "Next,
               className: "btn btn-success",
               callback: function(){
                   //some logic
               }
           }
       }
    });
    

    resourceObj is part of the JS global namespace in this example just to make everything simpler.