I have a page which lets me create and save a record. When I click Save, I want to stay on the same page, but have that page display an updated view model. The problem I'm having is that after I save, the GET parameters stay in the page URL.
When I run my application, I go to the "list records" page and click the "create new" button. That causes a GET request to EditRecord with the createNew parameter set to true. The request looks like localhost/Home/EditRecord?createNew=True
public ActionResult EditRecord(string id, bool createNew = false)
{
MyRecordViewModel viewModel;
if (createNew)
{
viewModel = new MyRecordViewModel
{
IsNew = true
};
}
else
{
var myRecord = (from p in this.context.MyRecords
where p.Id = id
select p).FirstOrDefault();
if (myRecord == null)
{
this.ErrorMessage("Cannot find record.");
return View();
}
viewModel = new MyRecordViewModel(myRecord);
}
return View(viewModel);
}
Then when I click save, it POSTs to this method
[HttpPost]
public ActionResult EditRecord(MyRecordViewModel viewModel)
{
// Save record to database
// ...
// Update the view model
viewModel.LastUpdatedDttm = DateTime.Now;
// Clear the model state dictionary so that my updated view model's values will be shown on the page
ModelState.Clear();
// Go back to the same page with an updated view model
return View(viewModel);
}
The updated page is displayed correctly with the updated view model. The problem is that the URL is still localhost/Home/EditRecord?createNew=True. I want the URL to be localhost/Home/EditRecord
I don't want to redirect back to the GET page with my record ID and with createNew equal to false, because that'll cause an unnecessary trip to the database in order to redisplay the same record.
GETpart involve a trip to database to select data that I already have available? I'm trying avoid unnecessary database access.