Find data with id from httpPost

get and post method in html examples
web api get method with parameters
pass multiple parameters in web api url c#
web api post method with multiple parameters c#
http post example
web api get parameters from body
web api get parameters from url
angular 7 http post example

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.

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>

Parameter Binding in Web API, Learn how Web API binds HTTP request data to the parameters of an action As you can see above Get action method includes id parameter of int type. if an HTTP POST request is http://localhost/api/student?id=1&name=steve then the  HttpGet and HttpPost, both are the method of posting client data or form data to the server. HTTP is a HyperText Transfer Protocol that is designed to send and receive data between client and server using web pages.

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);

Model Binding, To understand the model binding in MVC, first let's see how you can get the http For example, the query string "id" in the following GET request would Model binding in MVC framework automatically converts form field data of HttpPOST  Yes i know. my firt page is a get with id to show the infos about user, so i need a post to activate/deactivate, how would be the httppost call? – waldecir Dec 13 '10 at 13:25 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">&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>

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">&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>

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.

Get data from a server, HttpClient is Angular's mechanism for communicating with a remote server over `fetched` : `did not find`; this.log(`${outcome} hero id=${id}`); }), catchError(this. In this quick article, we will discuss step by step how to use Apache HttpClient 4.5 to make an HTTP POST request. The HTTP POST request method requests that the server accepts the entity enclosed in the request as a new subordinate of the web resource identified by the URI.

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 ?

Sending form data, As we'd alluded to above, sending form data is easy, but securing an label> <​input name="say" id="say" value="Hi"> </div> <div> <label Note: You can find this example on GitHub — see get-method.html (see it live also). For example, some commonly-used HTTP methods will retrieve data from a server, submit data to a server for processing, delete an item from the server's data store, etc. For a more general overview of HTTP, see Tutorials Point's article. Selecting The Appropriate Method

Entity Framework 6 Recipes, Find(id)); } } // POST: /Category/Edit/5 [HttpPost] public ActionResult Edit(int id, MyStoreEntities()) { db.Entry(categoryValue).State = System.Data.EntityState. addSmartphone(smartphone: Smartphone): Observable<Smartphone> { return this.http.post<Smartphone>(localUrl, smartphone, httpOptions) .pipe( catchError(this.handleError('addSmartphone', smartphone)) ); } Back to the Angular component, declare the data variable with a type and a variable for the response.

Professional ASP.NET MVC 3, The model binder can look at route data, the query string, the form collection, and you Model binding isn't restricted to HTTP POST operations and complex /​StoreManager/Edit?id=8, because the model binder will find the id parameter in  As we'd alluded to above, sending form data is easy, but securing an application can be tricky. Just remember that a front-end developer is not the one who should define the security model of the data.It's possible to perform client-side form validation, but the server can't trust this validation because it has no way to truly know what has really happened on the client-side.

Part 6, controller methods and views in ASP.NET Core, For more information, see Data Types. The HttpGet Edit method takes the movie ID parameter, looks up the movie using the Entity Framework  The HttpPost method that deletes the data is named DeleteConfirmed to give the HTTP POST method a unique signature or name. The two method signatures are shown below: // GET: /Movies/Delete/5 public ActionResult Delete(int? id) // // POST: /Movies/Delete/5 [HttpPost, ActionName("Delete")] public ActionResult DeleteConfirmed(int id)

Comments
  • " find good data from id " Do you mean to use id to get the data from the pokemonList that is populated in Index method ? " I do not have entity yet " Does it mean that you did not save the data in the Index method to the database? What is the logic between view and controller ? Could you share the more details on the view ?
  • Yes I have the Id of th selected Pokemon by a httpPost. My data are in the controller the data are not coming from A data base (sql)
  • Thank you but is I put var = JsonConvert.SerializeObject(pokemonList). This destroy my web site the design of it.
  • @AlexandreProd'Hon, this is just to save the pokemonlist to TempData. The model returned by your page is still the PokemonViewModel. It should not be affected. If there is the error message, could you share it?
  • This is my website with var json ... ibb.co/McmTmg0 ///// and this is my website without var json .... ibb.co/7n1FG0T
  • What is the design of the related views(Index view and partial view)? Did you press F12 to use browser developer tools to check if errors occurred?
  • this is when I use your code : ibb.co/3rQFCjd ////// The problem come only when I use TempData not var json = ...
  • I cant acces to pokeList from action httpPost
  • I solved the problem. In put an answer above.
  • which lines do you change ?
  • A lot look I post an answer