Get string from controller action

MattNorman

Well-known member
Joined
May 22, 2021
Messages
98
Programming Experience
1-3
I am trying to get a string back from a controller action when a user wants to retrieve a password.

I have it set up however I'm not sure how to get the returned string from the json data that is returned.

Can anyone point me in the right direction?

Table row
C#:
<td class="text-primary">******<i class="fa fa-copy" style="margin-left: 20px; color: white" onclick=" GetPassword(@Model[i].AccountId)"></i></td>

JavaScript
C#:
<script>
        function GetPassword(id)
        {
            $.ajax({
                url: "/Accounts/GetPassword",
                type: "GET",
                data: { "id": id },
                contentType: "application/json; charset=utf-8",
                datatype: "json",
                success: function (data) {
                    alert(data.value);
                },
                error: function () {
                    alert('error');
                }
            });
        }
    </script>

Controller Action
C#:
public ActionResult GetPassword(int id)
{
    return Json(new { data = $"Password for {id}" });
}
 
Solution
I wasn't quite expecting that. What does Fiddler or the browser's dev tools show as the response sent back by the controller?

What happens when you change to:
C#:
return Json($"Password for {id}");
Change line 11 to alert(data) tell us what you see.
 
I wasn't quite expecting that. What does Fiddler or the browser's dev tools show as the response sent back by the controller?

What happens when you change to:
C#:
return Json($"Password for {id}");
 
Solution
I wasn't quite expecting that. What does Fiddler or the browser's dev tools show as the response sent back by the controller?

What happens when you change to:
C#:
return Json($"Password for {id}");
That did the job. Thanks for your help as always.
 
I've not tried, but I suspect that alert(data.data); would have also worked.
 

Latest posts

Back
Top Bottom