0

Assume a simple model:

public class PostViewModel
{
    [DataType(DataType.Date)] public DateTime Start { get; set; }
    [DataType(DataType.Date)] public DateTime End { get; set; }
}

and a GET and a POST action:

[HttpGet]
public IActionResult Edit(PostViewModel viewModel)
{
    return View(viewModel);
}

[HttpPost]
[ActionName(nameof(Edit))]
public IActionResult EditPost(PostViewModel viewModel)
{
    viewModel.Start = DateTime.Today;
    viewModel.End = DateTime.Today.AddDays(7);
    return View(viewModel);
}

The response of the post always returns the posted values and not the ones manually set by me:


Edit View of PostViewModel

How to fix this behavior?

Marcel
  • 1,002
  • 2
  • 16
  • 37

1 Answers1

0

That is by design. You should only return a view from your post action if there's some sort of validation error that the user needs to correct. In which case, they need the values they posted to be shown (rather than defaults or whatever), so that they can correct their errors and resubmit.

If the result of the post action is successful, then you should instead redirect, even if it's to the same URL. This is what's referred to as the PRG (Post-Redirect-Get) pattern.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444