user2915962
user2915962

Reputation: 2711

Call method from view and receive its value:

I got this method that returns a random word from the list:

public string GetRandom()
{
    var firstNames = new List<string> {"Hund", "Katt", "Hus", "Bil"};

    Random randNum = new Random();
    int aRandomPos = randNum.Next(firstNames.Count);//Returns a nonnegative random number less than the specified maximum (firstNames.Count).

    string currName = firstNames[aRandomPos];

    return currName;
}

In my view, I would like to be able to call this method and display the value it returns. I cant figure out how, I can call the method like this:

@Html.ActionLink("GetRandom","GetRandom")

But how do I take care of its value and display it in the view?

Upvotes: 1

Views: 66

Answers (2)

User 12345678
User 12345678

Reputation: 7804

It would appear as though you will need to use Javascript in order to produce the effect that you describe in your latest comment.

  1. Alter your GetRandom method to return a JsonResult instead of a string:

    public ActionResult GetRandom()
    { 
        var firstNames = new List<string> { "Hund", "Katt", "Hus", "Bil" };
        Random randNum = new Random();
        int aRandomPos = randNum.Next(firstNames.Count);
        string currName = firstNames[aRandomPos];
        return Json(currName, JsonRequestBehavior.AllowGet);
    }
    
  2. Use jQuery to retrieve the data and display it in the label asynchronously (without a page refresh) each time the button is clicked:

    <p id="randomName">Random Swag</p>
    <button id="randomButton">Generate Name</button>
    
    <script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script>
         $("#randomButton").click(function () {
             $.get('/Home/GetRandom', function (data) {
                 $("#randomName").text(data);
             });
         });
    </script>
    

Upvotes: 2

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

Put your method in a class that is derived from Controller.

ActionLink, the first parameter is action name, the second parameter is controller name.

You want to call this way.

@Html.ActionLink("GetRandom", "GetRandom")

This is what you need to have.

public class GetRandomController : Controller
{
    public string GetRandom()
    {
        var firstNames = new List<string> { "Hund", "Katt", "Hus", "Bil" };

        Random randNum = new Random();
        int aRandomPos = randNum.Next(firstNames.Count);//Returns a nonnegative random number less than the specified maximum (firstNames.Count).

        string currName = firstNames[aRandomPos];

        return currName;
    }
}

Upvotes: 0

Related Questions