I am having trouble writing the code for saving a text field box information into the database and this is what I have – a Get and Post method:
public ActionResult _UserName(UserNameModel userNameModel)
{
using (var db = new DataConnection())
{
userNameModel.UserName= (from u in db.Users
where u.ID == WebSecurity.CurrentUserId
select u.UserName).FirstOrDefault();
}
return View(userNameModel);
}
}
[HttpPost]
public ActionResult _CreateUserName(string username, UserNameModel userNameModel)
{
if (ModelState.IsValid)
{
using (var db = new DataConnection())
{
try
{
// Need to save what has been entered in the textbox
// to the Users table in the database.
}
catch (Exception)
{
throw;
}
}
return RedirectToAction("UserNamePage");
}
return View(userNameModel);
}
You do not need to use
FormCollectionhere as it appears as if you are binding to a model.In the View you should have
Then when you submit the form you can get the model data from
userNameModel.Username;Your Post method only needs to collect the model data
Edit My preferred method for interacting with the database is to use Linq, in your project add a new item > Data > LinqToSql. This will give you a diagrammatic overview and you can simply drag tables and procedures to the screen. This will create a model of each table.
You can then create an instance of the Linq context and use this to update your database, you will see intellisense will pick up the tables in your designer. You will then be able to interact with the database very cleanly
If you want to Update you will need to call an Instance of the record in the database