从httpPost查找ID为的数据

时间:2019-09-18 21:57:03

标签: c# asp.net-core asp.net-core-mvc

我发了一个HttpPost:

[HttpPost]
public IActionResult PokemonDetails(int PokemonId)
{

    return PartialView("_PokemonDetails");
}

我想从http中的ID中查找所有数据。 数据在我的控制器中:

public IActionResult Index()
{
    #region ListeDesPokemons
    var pokemonList = new List<PokemonModel>();
    var Id = 1;
    var Img = 1;

    pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Bulbizarre", UsName = "Bulbasaur(us)", JpName = "フシギダネ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
    pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Herbizarre", UsName = "Ivysaur(us)", JpName = "フシギソウ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });

    #endregion

    var model = new PokemonViewModel();

    model.Pokemons = pokemonList;

    ViewBag.TotalPokemon1G = pokemonList.Count;

    return View(model);
}

从id中找到好的数据,谢谢。 我还没有实体。

4 个答案:

答案 0 :(得分:0)

您可以使用LINQ在列表中查询所需的ID。

int PokemonId = 2; // input from http post    
var result = pokemonList.FirstOrDefault(p => p.Id == PokemonId);

答案 1 :(得分:0)

您可以使用TempData在不同请求之间传递数据。TempData用于将数据从当前请求传递到后续请求(意味着从一页重定向到另一页)。它的寿命很短,只有等到目标视图完全加载后才能说谎。但是您可以通过调用Keep()方法将数据保留在TempData中。

这是一个简单的工作演示

型号:

public class PokemonModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string UsName { get; set; }
    public string JpName { get; set; }
    public string Type1 { get; set; }
    public string Type2 { get; set; }
    public int Rate { get; set; }

    public string Image { get; set; }
}

public class PokemonViewModel
{
    public List<PokemonModel> Pokemons { get; set; }
}

控制器:

public IActionResult PokemonList()
    {
        #region ListeDesPokemons
        var pokemonList = new List<PokemonModel>();
        var Id = 1;
        var Img = 1;

        pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Bulbizarre", UsName = "Bulbasaur(us)", JpName = "フシギダネ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
        pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Herbizarre", UsName = "Ivysaur(us)", JpName = "フシギソウ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });

        #endregion

        var model = new PokemonViewModel();

        model.Pokemons = pokemonList;
        var json = JsonConvert.SerializeObject(pokemonList);
        TempData["pokemonJson"] = json;

        ViewBag.TotalPokemon1G = pokemonList.Count;

        return View(model);
    }

    [HttpPost]
    public IActionResult PokemonDetails(int PokemonId)
    {
        var pokemonJson = TempData["pokemonJson"].ToString();
        TempData.Keep("pokemonJson");
        var pokemonList = JsonConvert.DeserializeObject<List<PokemonModel>>(pokemonJson);
        var pokemon = pokemonList.SingleOrDefault(p => p.Id == PokemonId);
        return PartialView("_PokemonDetails",pokemon);
    }

查看:

@model WebApplication1.Models.PokemonViewModel


<table class="table">
  <thead>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Pokemons[0].Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Pokemons[0].JpName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Pokemons[0].UsName)
        </th>

        <th></th>
    </tr>
  </thead>
  <tbody>
    @foreach (var item in Model.Pokemons)
    {
        <tr>
            <td>

                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.JpName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UsName)
            </td>
            <td>
                <input hidden  asp-for="@item.Id" />
                <a href="javascript:;" class="btnclick">PokemonDetails</a>
            </td>
        </tr>
    }
  </tbody>
</table>

<div id="pokemon"></div>
@section Scripts{ 
<script type="text/javascript">
    $(".btnclick").click(function () {
        var id = $(this).closest("td").find("input").val();
        $.ajax({
            type: "post",
            url: "/Home/PokemonDetails?PokemonId=" + id,
            success: function (result) {
                $("#pokemon").html(result);
            }
        });
    });

</script>  
}

PartialView

@model WebApplication1.Models.PokemonModel
<div>
<hr />
<dl class="dl-horizontal">
    <dt>
        @Html.DisplayNameFor(model => model.Id)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.Id)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.Name)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.Name)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.JpName)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.JpName)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.UsName)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.UsName)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.Type1)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.Type1)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.Type2)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.Type2)
    </dd>
    <dt>
        @Html.DisplayNameFor(model => model.Rate)
    </dt>
    <dd>
        @Html.DisplayFor(model => model.Rate)
    </dd>
</dl>
</div>

答案 2 :(得分:0)

好的,我在这里做到了。

我的控制器:

public IActionResult Index()
{
    #region ListeDesPokemons

    var pokemonList = new List<PokemonModel>();
    var Id = 1;
    var Img = 1;

    pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Bulbizarre", UsName = "Bulbasaur(us)", JpName = "フシギダネ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
    pokemonList.Add(new PokemonModel() { Id = Id++, Name = "Herbizarre", UsName = "Ivysaur(us)", JpName = "フシギソウ(jp)", Type1 = "Plante", Type2 = "Poison", Rate = 45, Image = "https://eternia.fr/public/media/pokedex/artworks/00" + Img++ + ".png" });
     var model = new PokemonViewModel();

    model.Pokemons = pokemonList;

    var json = JsonConvert.SerializeObject(pokemonList);

    TempData["pokemonListJson"] = json;
    TempData.Keep("PokemonListJson");

    ViewBag.TotalPokemon1G = pokemonList.Count;

    return View(model);
}


 [HttpPost]
public IActionResult PokemonDetails(int pokemonId)
{
    if (TempData["pokemonListJson"] != null)
    {
        if (string.IsNullOrEmpty(TempData["pokemonListJson"].ToString()))
        {
            return null;
        }
    }

    var pokemonListJson = TempData["pokemonListJson"].ToString();
    TempData.Keep("PokemonListJson");

    var pokemonList = JsonConvert.DeserializeObject<List<PokemonModel>>(pokemonListJson);
    var selectedPokemon = pokemonList.SingleOrDefault(p => p.Id == pokemonId);

    if (selectedPokemon != null)
    {
        return PartialView("_PokemonDetails", selectedPokemon);
    }

    return null;
}

我的局部视图:

@model PokemonModel
<div id="taillDescriptionModal" class="modal-dialog modal-dialog-scrollable mw-100 m-auto" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 id="modalLabelStack2" class="modal-title font-weight-bold float-left">n° @Html.DisplayFor(model => model.Id)</h5>
            <div id="nomPokemonStack2" class="ml-auto">
                <h5 id="Name">@Html.DisplayFor(model => model.Name)</h5>  <h5 id="UsName">@Html.DisplayFor(model => model.UsName)</h5> <h5 id="JpName">@Html.DisplayFor(model => model.JpName)</h5>
            </div>
            <button type="button" class="close" data-dismiss="modal" aria-label="close">
                <span class="text-danger" aria-hidden="true">&times;</span>
            </button>
        </div>
        <div class="modal-body">
            <div class="row">
                <div class="col overflow-hidden">
                    <img class="img-fluid rounded-lg" src="@Html.DisplayFor(model => model.Image)" alt="pokemon.Name" />
                </div>
                <div class="col">
                    <span>Type : </span>
                    <div class="col text-white">
                        <span class="@Html.DisplayFor(model => model.Type1) badge">@Html.DisplayFor(model => model.Type1)</span>
                        <span class="@Html.DisplayFor(model => model.Type2) badge">@Html.DisplayFor(model => model.Type2)</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
            <button type="submit" class="btn btn-success" onclick="afficheIdSurIndex(@Html.DisplayFor(model => model.Rate))"> Choisir</button>
        </div>
    </div>
</div>

<script>
    function afficheIdSurIndex(selectedPokemonRate) {
        $.ajax({
            url: '/Pokedex/Calcul/',
            type: 'POST',
            dataType: "html",
            data: { "selectedPokemonRate": selectedPokemonRate },
            success: function () {
                //enlever la classe pour afficher le contenu de la div
                $('#Test').removeClass('text-hide');
                //$('#Test').addClass('text-show');

                var rateTxt = 'Taux de Capture du pokémon sélectionné : ' + selectedPokemonRate
                //vider le contenu de la div
                $("#Test").empty();
                //écrire dans la div
                $("#Test").append(rateTxt);

                //fermer les modals
                $('#pokemonDetails').modal('hide');
                $('#choixPokemon').modal('hide');
            }
        })
    }
</script>

我的索引页面:

@model PokemonViewModel
@{
    ViewData["Title"] = "Pokedex";
    Layout = "~/Views/Shared/_LayoutPokemon.cshtml";
    <script src="~/lib/jquery/dist/jquery.min.js"></script>

}

<h1>Pokedex</h1>

<!-- Button choix Pokémon modal -->
<div class="container">
    <button type="button" class="btn btn-primary mb-2" data-toggle="modal" data-target="#choixPokemon">
        Pokemon 1G
    </button>
</div>

<!-- Modal choix Pokémon -->
<div id="choixPokemon" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="choixPokemonModalLabel" aria-hidden="true">
    <div id="modalWitdh" class="modal-dialog modal-dialog-scrollable mw-100 m-auto" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 id="choixPokemonModalLabel" class="modal-title">Pokédex première génération, @ViewBag.TotalPokemon1G Pokémons </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body text-center">
                <div class="row">
                    @foreach (var pokemon in Model.Pokemons)
                    {
                        <div class="col">
                            <button type="submit" class="btn" onclick="getInfo(@pokemon.Id)">
                                <div class="card text-center rounded-lg">
                                    <div id="tailleCard" class="card-body">
                                        <h5 id="cardTitle" class="card-title">n°@pokemon.Id <br /> @pokemon.Name</h5>
                                        <img id="tailleImg" src="@pokemon.Image" alt="@pokemon.Name" />
                                    </div>
                                </div>
                            </button>
                        </div>
                    }
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Fermer</button>
            </div>
        </div>
    </div>
</div>

<!-- Modal Description du pokémon choisi -->
<div id="pokemonDetails" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="descriptionPokemonModalLabel" aria-hidden="true">
    @*Contenue dans vu partiel _PokemonDetails*@
</div>

@*Div de collection des donnés du pokémon selectionné dans le deuxième modal.(données provenant de la vue partiel _PokemonDetails) *@
<div class="row">
    <div class="col">
        <h6 id="Test" class="text-hide"></h6>
    </div>
</div>

@*button script pour collecter les données du pokémon sélectionné dans le 1er modal*@
<script>
    function getInfo(pokemonId) {
        event.preventDefault;
        console.log(pokemonId);

        $.ajax({
            url: '/Pokedex/PokemonDetails/',
            type: 'POST',
            dataType: "html",
            data: { "pokemonId": pokemonId },
            success: function (response) {

                $("#pokemonDetails").html(response);
                $('#pokemonDetails').modal('show');
            }
        })

    }
</script>

在启动页面中,我需要添加:

services.AddMemoryCache();
services.AddSession();
services.AddMvc().AddSessionStateTempDataProvider();

我把所有东西都放在这里,以帮助需要帮助的人。

答案 3 :(得分:0)

在动作PokemonDetails中添加断点:

[HttpPost]
        public IActionResult PokemonDetails(int pokemonId)
        { // add break point here

在此处达到断点时,您得到了pokemonId吗?