Search code examples
asp.net-mvcentity-frameworkcode-first

Data Not Saved after click on submit button - MVC 5


After click on the sumbit button and trying to debug the code i don't recieve any error or exception but the data not saved I have a class called login ... need the user after click on login button save its data in the database This is my Post Action:

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(Login model, string returnUrl)
    {
        Context db = new Context();
        if (string.IsNullOrEmpty(model.LoginName))
        {
            this.ModelState.AddModelError("LoginName", "this field is required");
            return this.View(model);
        }
        try
        {
            if (ModelState.IsValid)
            {

                var user = new Login { LoginName = model.LoginName, LoginPassword = model.LoginPassword };
                db.Logins.Add(user);
                db.SaveChanges();
                return Redirect("http://www.google.com");
            }


            else
                return View();

        }
        catch (Exception e)
        {
            return View();
        }
    }

And this is my Login Class:

[Table("Login")]
public partial class Login
{
    public int ID { get; set; }

    [StringLength(50)]
    public string LoginName { get; set; }

    [StringLength(10)]
    public string LoginPassword { get; set; }
}

And this is my DBContext:

public class LoginContext : DbContext 
{
    public LoginContext () : base("LoginContext ")
    {
    }
    public virtual DbSet<Login> Logins { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

After return to the google link the data not saved.


Solution

  • After trying a lot of solution Finally i found that :

    1. When adding the Code first code i had make the DBContext with the same name of the table name "Login".

    2. Delete all of them then add the new code first "DBContext" and choose your DB.

    3. Will find that the DBConext will added automatically and your tables also will added. That will work correctly.