}
@code {
private WeatherForecast[] forecasts; //data list
private bool IsEditMode; //Specify the form mode
//define the following properties to add or edit item.
private DateTime ForeastDate;
private string TemperatureC;
private string[] Summaries;
private string Summary;
private int selectedid; //used to store the Edit item primary key.
//Set the initial data.
protected override async Task OnInitializedAsync()
{
IsEditMode = false; // set the default mode to Add Mode.
Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
ForeastDate = DateTime.Now;
forecasts = await Http.GetFromJsonAsync("http://localhost:5000/WeatherForecast");
}
//add new items to the data list
private void AddNewItem()
{
var rng = new Random();
//add new item in to the data list, you can also call the api to insert the data into database.
forecasts = forecasts.Append(new WeatherForecast() { Id = forecasts.Length, Date = ForeastDate, Summary = Summary, TemperatureC = Convert.ToInt32(TemperatureC) }).ToArray();
}
//save the Edit item.
private void SaveEditItem()
{
//find the item based on the primary key.
var selectedItem = forecasts.First(c => c.Id == selectedid);
//update the data.
selectedItem.Date = ForeastDate;
selectedItem.Summary = Summary;
selectedItem.TemperatureC = Convert.ToInt32(TemperatureC);
//change the mode from Edit to Add mode.
IsEditMode = false;
//clear the input value.
ForeastDate = DateTime.Now;
Summary = "";
TemperatureC = "";
}
//Edit Item.
private void EditItem(int id)
{
IsEditMode = true; //change the Mode from Add to Edit.
//based on the primary key to find the item.
selectedid = id;
var selectedItem = forecasts.First(c => c.Id == id);
//display the item's detailed information
Summary = selectedItem.Summary;
TemperatureC = selectedItem.TemperatureC.ToString();
ForeastDate = selectedItem.Date;
}
private async Task ShowPrompt()
{
bool confirmed = await JsRuntime.InvokeAsync("confirm", "Are you sure?");
if (confirmed)
{
// Delete!
}
}
}