[SOLVED] Assign a C# string to a ViewData, then pass the ViewData to the alert() to display an alert

Issue

I have this JS function in my .cshtml file. I need to pass the string from the C# Object to a JavaScript variable so that I can display the ReceiverName as an alert. I am kinda new to ASP.NET so I’m not quite sure whether this is the best way as C# and JS will have to be used together. Does anyone know a better approach as I am quite lost? This is my 1st question here so please if there’s any more info required I’ll be glad to answer : )


function autoFillForeign(){
        @{
            string custID = (string)ViewData["customerID"];
            PayeeListDAL payeeContext = new PayeeListDAL();
            List<PayeeList> payeeList = payeeContext.GetAllPayeeList(custID);
            ViewData["name1"] = payeeList[0].ReceiverName;
            @: alert(@ViewData["name1"])
        }
    } 

Solution

I didn’t quite get what you want to achieve but it is easy to pass values from C# to JavaScript. You can try out these approaches…

<script type="text/javascript">
     function autoFillForeign(){
        var msg = "@msg";
        alert(msg);
     }
</script>

and the C# variable might be declared any where above that function like below:

@{
     string msg = "You are learning good";
 }

Sometimes you might even want to get a value from C# function into JavaScript function, its still the same approach.

<script type="text/javascript">
   function autoFillForeign(){
      var msg = "@ShortenText(msg)";
      alert(msg);
   }
</script>

Your C# code might look something like below:

@functions{
    public string ShortenText(string txt)
    {

       return (txt.Length > 10)? txt.Substring(0, 10): txt;
    }
}

and your c# variable might be declared like

@{
   string msg = "I am not a new C# programmer; I started programming C# since 2016";
 }

Answered By – Ngutor Tsenongo

Answer Checked By – David Goodson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *