views:

45

answers:

2

I am trying to make a simple web app. I have a User table which is just an id, name, password and email. The id is a counter so thats assigned automatically. I have a User/Create action which adds a user to the database. They fill out their name, password and email and click submit.

My problem is that the field isn't submitting and what is stranger is, it is the exact same code I have for an "Entry" controller and that works fine..

Code:

public interface IUserRepository {
    IQueryable<User> FindAllUsers();
    User GetUser(int id);
    void Add(User user);
    void Update(User user);
    void Delete(User user);
}

...

public void Add(User user) {
    db.Users.InsertOnSubmit(user);
    db.SubmitChanges();
}

...

public ActionResult Create()
{
    return View();
} 

//
// POST: /User/Create

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(User user)
{

    if(ModelState.IsValid){
        try
        {
            _repository.Add(user);
            return RedirectToAction("Index");
        }
        catch
        {
            return View(user);
        }
    }
    else
    {
        return View(user);
    }
}

Does anyone know what is wrong? Just to clarify, the when submit is pressed, it loads the form again. It doesn't redirect back to the index.

+1  A: 

Yes. Most likely you need to alot for a primary key on your Post:

public ActionResult Create([Bind(Exclude="Id")] User user)
Nissan Fan
Nope, that didn't do anything.
GreenRails
Well you absolutely need to do this if you have a primary key on your database. Does your primary keep have an identity column? Make sure it does.
Nissan Fan
My primary key does have an identity column but I am not submitting an id with my form. The way I thought it works was that it just incremented the id on every database insertion?
GreenRails
Actually, I was too quick to dismiss this. My primary key DID have an identity column... but when I checked it, it didn't. Strange. I must have changed it by mistake. While I didn't use your solution, your comments prompted me to fix my problem so I marked it as correct. Thanks.
GreenRails
+1  A: 

Have you tried inserting a break point in Visual Studio at the start of your Create(User user) method, and then running the debugger? This is a good way to try and find out what is happening in this sort of situation.

I have sometimes found that the method I thought should be getting executed isn't even being called - in this case the break point will never be reached.

If the break point is reached, you can then hover over the variables in your code to see what values they have.

philwilks