Home > Software engineering >  Access String Value from TempData from Script Tag inside View
Access String Value from TempData from Script Tag inside View

Time:11-17

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"

CodePudding user response:

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

CodePudding user response:

You must use the ViewBag at .cshtml file parameter

Example:

@ViewBag.nameEntity
  • Related