There isn't a "proper" way as such, just different options that you can select from based on your use case.
The first is that you post all your data back to the controller i.e. add inputs for every property.
The second is to retrieve missing data again before resurfacing your form e.g.
[HttpPost]
public IActionResult SomeMethod([FromForm] SomeModel model)
{
if (!ModelState.IsValid)
{
model.Property = _repo.GetValue();
return View(model);
}
}
The third is to use TempData
or Session
, which work in a similar way.
TempData
might be better in this scenario, as the value is only persisted for a single HTTP request:
[HttpGet]
public IActionResult SomeMethod()
{
var value = _repo.GetValue();
TempData["value"] = value; // Store value in temp data
model.Property = value;
return View(model);
}
[HttpPost]
public IActionResult SomeMethod([FromForm] SomeModel model)
{
if (!ModelState.IsValid)
{
model.Property = TempData.Peek("value"); // Retrieve from temp data (may need casting)
return View(model);
}
}
Notice the use of TempData.Peek
rather than accessing by key; this will ensure if another submit is invalid, the data will be retained, then will be cleared once a valid submission is made.
Be aware that when using the TempData
/ Session
approach that multiple windows / tabs may overwrite the data, which will then resurface in another tab.
Also a session may timeout, which would cause values to be lost.