How does the corresponding value display?
I select the stage I have created.
And I want the corresponding price of the stage to be displayed after I select the stage, what should I do?
This is my code:
<div >
<label asp-for="PricelistId" ></label>
<select asp-for="PricelistId" class ="form-control" asp-items="ViewBag.PricelistId"></select>
</div>
<div >
<label asp-for="Price" ></label>
<input asp-for="Price" />
<span asp-validation-for="Price" ></span>
</div>
PricelistId is the foreign key I reference from the Price list in first pic
CodePudding user response:
You only shared a very small piece of your code so I created new project to demonstrate how you can do what you want.
Fruit.cs
public class Fruit
{
public string Id { get; set; }
public string Name { get; set; }
public int Price { get; set; }
}
Index.cshtml.cs
public class IndexModel : PageModel
{
private readonly List<Fruit> _fruitList = new()
{
new Fruit { Id = "1", Name = "Banana", Price = 200 },
new Fruit { Id = "2", Name = "Apple", Price = 47 },
new Fruit { Id = "3", Name = "Orange", Price = 75 },
new Fruit { Id = "4", Name = "Lemon", Price = 123 },
};
[BindProperty]
public string SelectedFruit { get; set; } = "1";
public int? SelectedFruitPrice =>
_fruitList.FirstOrDefault(x => x.Id == SelectedFruit)?.Price;
public SelectList Options { get; set; }
public void OnGet()
{
Options = new SelectList(_fruitList, "Id", "Name");
}
public void OnPost()
{
Options = new SelectList(_fruitList, "Id", "Name");
}
}
Index.cshtml
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<div >
<div >
<form method="post">
<div >
<select onchange="this.form.submit()" asp-for="SelectedFruit" asp-items="@Model.Options"></select>
</div>
</form>
<input value="@Model.SelectedFruitPrice" />
</div>
</div>
Basically I added onchange="this.form.submit()"
to the <select>
element so every time it changes it submits a form that sets the SelectedFruit
property. Then based on SelectedFruit
property I calculate the SelectedFruitPrice
and show this value inside an <input>
element.
You can find the project here: https://github.com/Jimmys20/SO73601166