skip to Main Content

I’m trying to access string value from TempData from the script tag inside .cshtml file.

<script>  
    var FromComTaskLibType = '@TempData["FromComTaskLibType"]';
    console.log(FromComTaskLibType.toString())    
</script>

Using this, I am getting value as AAAA instead of getting like 'AAAA'. I have called them with .toString(). Still it is not working.

In controller, I am assigning this value like this:

public ActionResult LoginFromCOM(string libType)
{                  
    TempData["FromComTaskLibType"] = libType;
    //...
}

Here value of libType is coming as "AAAA"

2

Answers


  1. You must use the ViewBag at .cshtml file parameter

    Example:

    @ViewBag.nameEntity
    
    Login or Signup to reply.
  2. Using this, I am getting value as AAAA instead of getting like ‘AAAA’.
    I have called them with .toString(). Still it is not working.

    Well, you don’t need to convert to string as TempData already a string. So you could try following way.

    Controller:

    public class AccessTempDataController : Controller
            {
                
                public ActionResult LoginFromCOM(string libType)
                {
                    TempData["FromComTaskLibType"] = libType;
                   return View();
                }
            }
    

    Script:

    <script>
        var FromComTaskLibType = '@TempData["FromComTaskLibType"]';
        alert(FromComTaskLibType);
        console.log(FromComTaskLibType);
    </script>
    

    Output:

    enter image description here

    If You Want This ‘AAAA’ Output:

    However, if you want your output as 'AAA' with single qoute You have to parse the string into JSON.stringify then has to replace the double qoute into single qoute as following:

    <script>
        var FromComTaskLibType = '@TempData["FromComTaskLibType"]';
        alert(JSON.stringify(FromComTaskLibType));
    
        var data = JSON.stringify(FromComTaskLibType);
        alert(data.replace(/"/g, '''));
        console.log(data);
    </script>
    

    Output:

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search