jeudi 20 octobre 2016

Sending List from View to Controller results in null List in MVC

I'm trying to create a List of users in MVC, where there's a button to add users generated randomly and there's a delete button for each user to erase them from the list. I send it from the Controller to the View and it generates one user. When I try to add one more, it just changes it. I guess it deletes the items in the List. I'm trying to pass the list back to the Controller, but it doesn't work. Can someone help please?

My Model:

public class UsersClass
{
    public int Code { get; set; }
    public string Name { get; set; }

    public UsersClass(int Code, string Name)
    {
        this.Code = Code;
        this.Name = Name;
    }
}

My Controllers:

List<UsersClass> UsersList = new List<UsersClass>();
public ActionResult Index()
{
    return View(UsersList);
}

[HttpPost]
    public ActionResult AddUser(List<UsersClass> UsersList)
    {
        if (UsersList == null)
        {
            int a = 123;
            UsersList = new List<UsersClass>();
        }
        Random generator = new Random();

        string[] vez_nevek = new string[10] { "Kovács", "Szekeres", "Király", "Szabó", "Vicha", "Kozma", "Ferencz", "Pócsi", "Tinka", "Horváth" };
        string[] ker_nevek = new string[10] { "Lajos", "Barnabás", "Róbert", "Balázs", "János", "Béla", "Petra", "Anna", "Ferenc", "Attila" };

        string vezetek_nev = vez_nevek[generator.Next(vez_nevek.Length)];
        string kereszt_nev = ker_nevek[generator.Next(ker_nevek.Length)];

        UsersList.Add(new UsersClass(generator.Next(100000, 999999), vezetek_nev + " " + kereszt_nev)); 

        return View("~/Views/UserManagement/Index.cshtml", UsersList);
    }

And my View to add a user:

<h2>User Management</h2>

@using (Html.BeginForm("AddUser", "UserManagement", FormMethod.Post)) {

int index = 0;
foreach (var item in Model)
{
    Html.Hidden("item[" + index + "].Code", item.Code);
    Html.TextBox("item[" + index + "].Name", item.Name);
    index++;
}
<input type="submit" value="Add User" />

}

Aucun commentaire:

Enregistrer un commentaire