Search code examples
c#asp.net-mvcasp.net-coremodel

How to retrieve the previous Model in the POST in MVC C#?


I have a View called MyVideos in which there is a list of videos and a list of comments. This is its IActionResult:

MyModel model = new MyModel();
model.videos = DB.GetVideos();
model.listOfComments = DB.GetComments();
model.comment = String.Empty;
return View(model);

I would like an user to upload a comment, and this is how I did it:

cshtml

    <form method="post" action="SubmitComment">
        <div class="form-group">
            <textarea class="form-control" id="exampleFormControlTextarea1" asp-for="comment"></textarea>
        </div>
        <button type="submit">Submit</button>
    </form>

cs

    [HttpPost]
    public IActionResult SubmitComment(MyModel model)
    {
        string videoId = ...
        DB.uploadComment(videoId, model.comment);
        model.videos = DB.GetVideos();
        model.listOfComments = DB.GetComments();
        return View("MyVideos", model);
    }

As you see, I am forced to retrieve model.videos again when I am just uploading a comment. Is there a way to retrieve the old model's data here? Thank you.

Tried to search for similar questions without success. I am sorry if it's naive.


Solution

  • How about creating an action to retrieve the model's data and showing the MyVideos view?

    Then you can DB.uploadComment(videoId, model.comment);, and return RedirectToAction that action. In that action you retrieve the old model's data and new data. Then you don't need to retrieve model.videos again when just uploading a comment.

    You can read Processing the POST Request to know more.