Search code examples
asp.net-core.net-corerazor-pages

Razor Pages Core - Update Model or pass additional data back to Post Method


I hope I can ask this question concisely...

Pretty new to Razor Pages using .Net Core but started a project and hope I can find help on a current problem. I am sure there may be a few ways of solving this problem so think it best to describe what I am looking to achieve compared to what I currently know.

To give a bit more detail, I have a Model called Entry. Each Entry can have many EntryImages. So, In my Razor Pages project, on the edit screen for Entries, I want to be able to add new EntryImages (one at a time).

So, on the Entry Edit page, I have a modal popup containing a file selector which allows me to pass an image file back to the Post method on Submit using IFormFile:

enter image description here

In code behind I then take this file and put the image info into an EntryImage which goes into the Entry, before passing to the database:

enter image description here

However, I also want to be able to add a comment against the image I have just passed to the database. This is where my understanding falls short. I hoped I could just update the Model in the page like so (this is a test example):

enter image description here

Where I try to add a new EntryImage to the model Entry - but back in the post method in code behind, the model does not contain the new EntryImage added.

I know my attempt is messy but hope it gives a good idea of what I am looking to achieve. I feel there is a really simple way of doing what I need but for trying, I cant seem to find the right answer yet.


Solution

  • You can have another input text behind the file selector:

    <div class="form-row">
        <div class="form-group">
            <input name="files" type="file" />
        </div>
    </div>
    <div class="form-row">
        <div class="form-group">
            <input name="comment" type="text"  />
        </div>
    </div>
    

    Then in the post method, have another parameter to accept the comment value:

    public async Task<IActionResult> OnPostAsync(IFormFile files, string comment)
    {
      //...
    }