Home > database >  Asp.net Core Razor persist data in a view over reload
Asp.net Core Razor persist data in a view over reload

Time:05-26

In my Razor app I can add in the details below and return the Result in a list, as well as area and cost. How do I persist that list of Results so it saves multiple results?

enter image description here

I am posting the results as

<form method="post"> 

and using the carpet class as

    [BindProperty(SupportsGet = true)]
    public Carpet? carpet { get; set; }

My OnPostAsync is

public async Task<IActionResult> OnPostAsync()
    {
        if (ModelState.IsValid)
        {
some code....
carpet.FinalCost = carpetOperations.TotalInstallCost(carpet);
carpet.Results.Add("Room area "   carpet.RoomArea   "sqm $"   carpet.FinalCost);
        }
        return Page();
    }

But I want to persist the data in my carpet.Results List across different entries.

I have also tried it as a Property

  public List<string> CarpetResults { get; set; }

and instantiated it in the constructor

 public IndexModel(ILogger<IndexModel> logger)
    {
        _logger = logger;

        CarpetResults = new List<string>();
    }

But it still resets after every page load.

CodePudding user response:

I suggest you to use Database to achieve this, Every time the page loads. it reads the data from the database, So it will not resets after every page load.

Because you don't provide enough code, So i can just write a simple demo to show.

//I use this simple class to create the database
public class Carpet
    {
        public int Id { get; set; }
        
        public int Area { get; set; }
        public int Cost { get; set; }
        //this property will save the "Room area xx sqm $ xx" 
        public string Text { get; set; }
    }

Then in PageModel

        //this property will show results in page
        [BindProperty]
        public List<Carpet> carpets { get; set; }
  
        //this property will pass data from page to controller
        [BindProperty]
        public Carpet carpet { get; set; }
        public IActionResult OnGet()
        {
            carpets = _context.carpets.ToList();
            return Page();
        }

public async Task<IActionResult> OnPostAsync(Carpet carpet)
    {
        if (ModelState.IsValid)
        {
            //........your code
            
            
            carpet.Text = "Room area "   carpet.Area   "sqm $"   carpet.Cost;
            _context.carpets.Add(carpet);
        }
        return Page();
    }

In page, You can use @foreach(xx) to get the items in List<Carpet>, Then display them on the page

@*your page code*@


<h1>results</h1>
@foreach (var item in @Model.carpets)
{
    <div>
        <h5>@item.Area</h5>
         <h5>@item.Cost</h5>
         <h5>@item.Text</h5>
    </div>
}

I just wrote a simple demo, you may need to add your css and js. You can also use session to achieve it, But I think it's easier to use a database.

  • Related