mardi 28 juillet 2020

ASP.NET CORE WEB - How To extract the Id from a Razor View ("Id is in IEnumerable")

Probably my approach to this is bad, but at least I wanna find out, if there is a Solution to my problem. I want to extract the Id from the Razor View, so I can use it in the Controller/Action.

@model HomeViewModels
@inject SignInManager<ApplicationUser> signInManager;
<body>
    <div class="container">
        <div class="comedy">
            <h3>Comedy</h3>
            @foreach(var books in Model.BooksDisplayedInStore)
            {
                @if (books.BookGenre == "Comedy")
                {
                        <div>
                            <p>@books.BooksInStore</p>

                            @if (signInManager.IsSignedIn(User))
                            {
                                <form method="post" asp-controller="Home" asp-action="DisplayBooks">

                                    **<input asp-for="@books.Id" type="hidden" />
                                    <input asp-for="@books.BooksInStore" type="hidden" />**

                                    <label asp-for="BooksOrdered">Nr Books:</label>
                                    <input asp-for="BooksOrdered" />
                                    <span asp-validation-for="BooksOrdered"></span>
                                    <input type="submit" value="Buy" />
                                    <br />
                                    <div asp-validation-summary="All"></div>
                                </form>
                            }   
                        </div>
                }
            }
        </div>

So as you can see I'm using an IEnumerable in my ViewModel, to access the objects from the database. But I don't know how to access the Id from that specific object that I select on the Razor View. The Id that I need to use in the Controller/Action. I did try something like this: I created an Id inside my ViewModel and tried to use it like this:

@{
Model.BookId = books.Id
}

which of course failed. Probably should change this approach. Anyone knows more ? Thank you.




Aucun commentaire:

Enregistrer un commentaire