killgore_bot
killgore_bot

Reputation: 71

How to store data in a hidden field and the pass it between pages in razor pages

So I am trying to select a value from dropdown list and passing it as query string in a another view this works fine on get but for post I want to store it in a hidden field

<div style="margin: 30px">
     <label asp-for="DropDown" class="control-label">DropDownList</label>
     <select asp-items="Model.dropdown" 
             asp-for="targetvalue" 
             value ="targetvalue" 
             type="hidden" class="form-control">
     </select>

Not sure if this is correct how do I retrieve the hidden field to use it in post

Upvotes: 1

Views: 1748

Answers (2)

VoidA313
VoidA313

Reputation: 546

You can use any of below methods, But the recommended way is "Model Binding".

  1. You can access the value by passing the key as an indexer to the Request.Form collection, like below:

    var number = Request.Form["targetvalue"];
    
  2. Add a suitable property to the PageModel and to allow model binding to apply the posted value to the property: like below:

       public IndexModel : PageModel
       {
          [BindProperty]
          public int targetvalue { get; set; }
          public void OnPost()
          {
               // posted value is assigned to the targetvalue property automatically
          }
       }
    

For this example the Drop-down list can be rendered in different ways, But once it rendered into HTML it would look like below:

<select name="targetvalue">
    <option value="">Select a number</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

Upvotes: 1

Jeremy Lakeman
Jeremy Lakeman

Reputation: 11100

IMHO, you should bind the value to a page model field, then just generate a hidden input in your form;

<input type="hidden" asp-for="targetvalue" />

Upvotes: 2

Related Questions