When adding a new entry into the db, I would like to grab an ID value to be entered from a previous page. I have no problem passing the ID from initial page into the controller create method which displays the view of the submission form. But I am not sure how I can access it after the form is submitted.
I have tried using TempData, ViewData and ViewBag, but I don't see the value when trying to retrieve it in the second method.
[HttpGet]
public IActionResult Create(int? id){
// I see the value here
Debug.WriteLine(id);
TempData["carid"] = id;
Debug.WriteLine(TempData["carid"]);
return View(); // displays new entry form
}
// called after the new entry form is submitted
[HttpPost]
public async Task<IActionResult> Create(RecordsViewModel addRecord)
{
// NO value here
var carId = TempData["carid"];
Debug.WriteLine(carId);
var record = new Records()
{
ID = carId, // value here is null
Date = addRecord.Date,
Name = addRecord.Name,
Cost = addRecord.Cost,
};
await carRep.Records.AddAsync(record);
await carRep.SaveChangesAsync();
return RedirectToAction("Create");
}
Any guidance is greatly appreciated, thanks!


Create Postdo you want to pass the ID toCreate(int? id)Get right? Or Opposite one?TempDatais meant to be a one-time use. After reading the value once it would be lost. Make sure that there isn't any other code in your application that might be clearing TempData.HttpContext.Session.SetInt32("carid", id);within your first action it can perist the value and then you can access it later on like thisvar carId = HttpContext.Session.GetInt32("carid");IActionResult Create(int? id)where I see the value. Second method -Task<IActionResult> Create(RecordsViewModel addRecord), where I'm trying to retrieve the value.HttpContext.Session.SetInt32("carid", (int)id);while I am trying to test your scenario and preparing answer.