Reputation: 2711
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
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.
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);
}
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
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