Pokimon
Pokimon

Reputation: 15

Refresh page execute post method

I am learning asp.net mvc framework

I create page with form. Data from this form going into database. Then i return this page to user with all data from database. Easy

Ok.

Ok. But, then user refresh page, post method executes again with same form data and another data write to database. WTF?

Here code:

Controller:

public class MainController : Controller
{
    [HttpGet]
    public ActionResult Index()
    {
        return View(db.Entries.ToList());
    }

    [HttpPost]
    public ActionResult Index(Message msg)
    {
        db.Entries.Add(msg);
        db.SaveChanges();

        return Index();
    }

    private MessagesContext db = new MessagesContext();
}

View:

@using BasicWeb.Models
@model List<Message>
@{
    ViewBag.Title = "Index";
}

<h2>Сохранялка</h2>

<form method="post" action="">
    <fieldset>
        <legend>Введи бурду</legend>
        <input type="text" name="UserName" maxlength="512"/>
        <input type="submit" value="ВВОДИ МЕНЯ"/>
    </fieldset>
</form>
<br />
@foreach(Message item in @Model)
{
    <p>@item.UserName</p>
}

Upvotes: 0

Views: 4370

Answers (2)

Yair Nevet
Yair Nevet

Reputation: 13003

By refreshing the page after a POST request, you are actually re-submitting your form.

As a better practice, after submitting the form, make sure to redirect the user to the same form but as a GET request.

Read more about it here: Post/Redirect/Get (PRG)

Upvotes: 4

Siva
Siva

Reputation: 386

You may want to track if the request is because of the page refresh.

Following may be helpful: Page Refresh Causes Duplicate POST in ASP.NET Applications

You will need to check if the request is because of postback or pagerefresh.

Upvotes: 0

Related Questions