Search code examples
c#asp.netasp.net-corerazorrazor-pages

How to display database information on webpage using Razor-pages


This is the image of database I'm working with

I want to display the "word" but using only the "id". If I have the id "11111", I need to display the word "abascus"

This is what I have done so far:

//This is the code behind file (.cshtml.cs)
public IList<testdiceware> testdiceware { get; set; }
public async Task OnGetAsync()
{
    testdiceware = await _db.testdiceware.ToListAsync();
}

This is how I'm trying to display information

//This is the .cshtml where I'd like to display the result
@Html.DisplayFor(model => model.testdiceware[11111].word);

This gives me ArgumentOutOfBounds exception probably cause it's referring to this value (marked in red), but I want to display the "word" corresponding to the "id" value

The main hurdle I'm facing is:

I'm generating the number '11111' and I need a way to display the corresponding word only using the generated number '11111', is there a way to achieve that?


Solution

  • For testdiceware[index].word,the value in [] should be the index of list testdiceware,you cannot put 11111 into it.The exception ArgumentOutOfBounds is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.You can try to use

    @Html.DisplayFor(model => model.testdiceware[0].word);
    

    to get word of the first testdiceware.

    Update:

    you can try to use:

    @Model.testdiceware.Where(t => t.id == 11111).ToList()[0].word