问题
I made a HttpPost :
[HttpPost]
public IActionResult PokemonDetails(int PokemonId)
{
return PartialView("_PokemonDetails");
}
I want to find all the data from the Id in the http. the datas are in my controller :
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);
}
find good data from id thank you. I do not have entity yet.
回答1:
You could use TempData
to pass data across different requests .TempData is used to pass data from current request to subsequent request (means redirecting from one page to another). It’s life is very short and lies only till the target view is fully loaded. But you can persist data in TempData by calling Keep() method.
Here is a simple working demo
Model:
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; }
}
Controller:
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);
}
View:
@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:
You can use LINQ to query the list for the Id you want.
int PokemonId = 2; // input from http post
var result = pokemonList.FirstOrDefault(p => p.Id == PokemonId);
回答3:
Ok I made it here is the answer.
My controller:
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;
}
My partial View:
@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">×</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>
My Index page:
@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">×</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>
In the startup page I need to add:
services.AddMemoryCache();
services.AddSession();
services.AddMvc().AddSessionStateTempDataProvider();
I put everything here for help anyone who need help.
回答4:
add a breakpoint in action PokemonDetails:
[HttpPost]
public IActionResult PokemonDetails(int pokemonId)
{ // add break point here
when the break point is hit here, did you get pokemonId ?
来源:https://stackoverflow.com/questions/58001231/find-data-with-id-from-httppost