简体   繁体   中英

Access String Value from TempData from Script Tag inside View

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"

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:

在此处输入图像描述

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:

在此处输入图像描述

You must use the ViewBag at.cshtml file parameter

Example:

@ViewBag.nameEntity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM