Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Assign a C# string to a ViewData, then pass the ViewData to the alert() to display an alert

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"])
        }
    } 
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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";
 }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!