0

I have a small project that I have started working on in order to learn ASP.net and specifically the razor pages. I have a form to add some data to a list on the page. The issue is that I have not been able to find a way to take the existing model and simply re-display it. My current solution is to simply re-query the data then append the new data to display

ASP form:

 <form method="post"> 
       <input type="submit" asp-page-handler="AddData" />
 </form>

CodeBehind:

 public class IndexModel : PageModel
  {
    public SampleIndexModel sampleModel;

   public void OnPostAddData()
   {
     sampleModel = new SampleIndexModel();
     AddRandomData();
     UpdateModel();
   }

This works fine for sample data that is not from a database. I would like to avoid going to the database for data that I already have in memory -- so my goal is something like:

   public void OnPostAddData(SampleIndexModel currentData)
   {
     sampleModel = currentData;
     AddRandomData();
     UpdateData();
   }
1
  • 1
    You will have to preserve that model through requests, this means that you'll have to serialize it or add it as fields or something. Commented Aug 23, 2018 at 15:51

1 Answer 1

2

You in fact don't have that data in memory. That is your issue. Your Razor page is instantiated and disposed with each request, which of course means that your sampleModel ivar is then unitialized on the next request. To have it passed back, you would need to ensure that all the data was posted back, which means creating inputs in your form for each property.

However, that is anti-pattern. Not only should you not be maintaining state in this way, but it also opens your app up to manipulation, as the values could be modified by the client. If you then just accept the posted object as what you had before, you can introduce all sorts of security issues.

Long and short, requery the data. That is the best and safest approach. If your query is particular complicated, it may be worthwhile to cache it instead, but bear in mind that there's a cost to pulling from cache as well, particularly if you're doing the right thing and using a distributed cache like Redis or SQL Server. You'll have to evaluate whether using cache is actually any more efficient than simply making the query.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you -- that answers my question very well. Thanks for taking the time to explain it as well -- many of the other pages I have been reading online make more sense. I was not thinking about it correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.