Answer the question
In order to leave comments, you need to log in
How to store information in a Sheet in ASP.NET MVC 4.0?
Hello.
I am new to MVC.
I have such a class.
class UserInfo
{
public string Name{get;set;}
public string Surname{get;set;}
}
public class HomeController : Controller
{
//
// GET: /Home/
List<UserInfo> Users = new List<UserInfo>();
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(UserInfo userInfo)
{
if (ModelState.IsValid)
{
Users.Add(userInfo);
return RedirectToAction("Index");
}
return View();
}
}
Answer the question
In order to leave comments, you need to log in
Because you apparently have different instances of controllers. Make the Users field static eg.
The model class must also be public.
I advise, as a beginner, to go through two manuals on asp.net mvc 3/4 located on the official website - on one cd disk store and video
catalog www.asp.net/mvc/tutorials/mvc-4/getting-started-wi...
www.asp.net/mvc/tutorials/mvc-music-store/mvc-musi...
They will explain you well what and how, but, unfortunately, only the basics, then you have to climb into the jungle yourself.
, then you can, for example, contact me, I, in principle, started working with all this not so long ago and now I am writing my own version of home web accounting on asp.net mvc5, but I will try to help
Hello. I agree with @foxmuldercp - the materials are helpful.
a static field in a controller is the worst possible solution. The MVC architecture assumes a model, which you ignore. The controller must work with a certain repository in terms of extracting and saving data. I will give a simplified example
public interface IUsersRepository
{
UserInfo SaveUserInfo(UserInfo user);
IReadOnlyCollection<UserInfo> GetUsers();
}
public class HomeController : Controller
{
private readonly IUsersRepository _usersRepository;
public HomeController()
{
_usersRepository = new UsersRepository();
}
public ActionResult Index()
{
var users = _usersRepository.GetUsers();
return View(users);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(UserInfo userInfo)
{
if (ModelState.IsValid)
{
_usersRepository.SaveUserInfo(userInfo);
Users.Add(userInfo);
return RedirectToAction("Index");
}
return View();
}
}
I didn’t understand, but who will transfer the model to the View, Uncle Vasya or what?
You are calling your index without a model. This is the first.
Second, as already mentioned: with each new request to the server, a new instance of the controller is created. Those. when a user is created, the first controller is created and the user is added to its list.
Calling Index creates another controller whose list is empty. So implement a storage for testing, like a static MemoryUserRepository class, and stick your leaf in there.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question