So I'm creating a basic MVC ASP.NET app that creates friends, displays them and allows you to edit the friends information.
The model is a Friend class with each friend having their own name, id, place, and position.
public class FriendModel
{
[Required]
public int id { set; get; }
[Required]
public String mesto { set; get; }
[Required]
public String name { set; get; }
public int pos { set; get; }
}
Whenever I add a new friend it in a List inside the FriendList object which is created once as a static when the controller is launched:
public class FriendList
{
private List<FriendModel> lista;
private int count;
public FriendList()
{
lista = new List<FriendModel>();
count = 0;
}
public FriendModel getEl(int i)
{
return lista.ElementAt(i);
}
public void add(FriendModel m)
{
m.pos = count;
count++;
lista.Add(m);
}
public List<FriendModel> getList()
{
return lista;
}
}
Inside the controller the HttpGet and HttpPost actions look like this:
[HttpGet]
public ActionResult Edit(int id)
{
FriendModel fm = lista.getEl(id);
return View(fm);
}
[HttpPost]
public ActionResult Edit(FriendModel fm)
{
FriendModel model = lista.getEl(fm.pos);
model.id = fm.id;
model.name = fm.name;
model.mesto = fm.mesto;
return Redirect("/Friend/ShowAll");
}
And the edit view look like this:
@model Lab1.Models.FriendModel
@{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (Html.BeginForm())
{
<label>Name</label><br />
<div>@Html.TextBoxFor(m => m.name)</div>
<label>Id</label><br />
<div>@Html.TextBoxFor(m => m.id)</div>
<label>Place</label><br />
<div>@Html.TextBoxFor(m => m.mesto)</div>
<br/>
<label>@Model.pos</label>
<input id="Submit1" type="submit" value="Edit" />
}
The problem is that whenever I edit something it doesn't make changed to the selected item I want to edit but always the first item in the list is being edited with the information I've edited in the selected item while the selected item is not being edited.
I suspect the problem comes in this area here in the controller:
[HttpPost]
public ActionResult Edit(FriendModel fm)
{
FriendModel model = lista.getEl(fm.pos);
model.id = fm.id;
model.name = fm.name;
model.mesto = fm.mesto;
return Redirect("/Friend/ShowAll");
}
Specifically in this line of code:
FriendModel model = lista.getEl(fm.pos);
It seems to be getting the object at the 0 position of the list instead of the selected position.
Any ideas?