CoreyD CoreyD - 1 month ago 8
C# Question

GET method executing before POST method after a page submit?

After editing a form and clicking a Save button, the HttpGet method is being executed before the HttpPost method. The page is reloading with the query string in the URL, and the old data still populating the fields, but the data has been saved on the server side. If I remove the query string and reload the page, the new data appears.

My expectation is that only the HttpPost method would be called, changes would be saved saved, then the page would be loaded back up with the saved changes.

Using the

Microsoft.AspNetCore.Mvc": "1.0.0
package.

Here are my
HttpGet
and
HttpPost
methods:

[HttpGet]
[Route("~/Home/Activity/{activityId}")]
public IActionResult Activity(int activityId)
{
ViewData["Title"] = "Activity Detail";


FundraiserDBContext context = new FundraiserDBContext(_ServerName, EnvironmentCode);
Engagement activity;

if (activityId == -1)
{
activity = new Engagement();
context.Engagement.Add(activity);
}
else
{
activity = context.Engagement.FirstOrDefault(a => a.Id == activityId);
}

if (activity != null)
{
ActivityViewModel vmActivity = new ActivityViewModel(activity, context);
return View("Activity", vmActivity);
}
else
{
ActivityViewModel vmActivity = new ActivityViewModel(context);
return View("Activity", vmActivity);
}
}

[HttpPost]
[ValidateAntiForgeryToken]
//[Route("~/Home/Activity/{activityId}")]
public IActionResult Activity(ActivityViewModel vmActivity)
{
FundraiserDBContext db = new FundraiserDBContext(_ServerName, EnvironmentCode);

if (ModelState.IsValid)
{
db.Engagement.Update(vmActivity.ToEngagement(db));
db.SaveChanges();
}

return View("Activity", vmActivity); //this was vm.EngagementId
}


And here is the code for the Save button:

<button type="submit" class="btn-success pull-right" style="width:80px;" onclick="location.href='@Url.Action("Activity", "Home", @Model)'">Save</button>

Answer

MatjaĆŸ Mav found my error and described it in the comment below the original post. I mistakenly thought I needed the onclick event on my button. Removing this resulted in the expected behavior I was looking for.

The button code now looks like this:

<button type="submit" class="btn-success pull-right" style="width:80px;">Save</button>
Comments