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.
- Display page with form. Ok
- Write data from this form to databse. Ok
- Read data from databse and display it to user. 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>
}