Lim
Lim

Reputation: 131

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"

Upvotes: 0

Views: 482

Answers (2)

Md Farid Uddin Kiron
Md Farid Uddin Kiron

Reputation: 22495

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

Upvotes: 1

Sajjad Emami
Sajjad Emami

Reputation: 11

You must use the ViewBag at .cshtml file parameter

Example:

@ViewBag.nameEntity

Upvotes: 0

Related Questions