0

I'm trying to understand the basics of MVC. I implemented a simple CRUD that works just fine, but I don't understand how the "Update" part works.

My model class is very simple :

public class User
{
    public int Id { get; set;
    public string Name { get; set; }
    public string Mail { get; set; }
}

Here are the two controller actions that I use for updating :

//id is passed through the url (action/controller/id)
public ActionResult UpdateUser(int id)
    {
        Models.User userToUpdate = Data_Services.DataServices.GetUserById(id);
        return View(userToUpdate);
    }

    [HttpPost]
    public ActionResult Updateuser(Models.User userToUpdate)
    {
        Data_Services.DataServices.UpdateUser(userToUpdate);
        return RedirectToAction("Index");
    }

The DataServices class performs some basic database stuff. Now here is the thing : I made a mistake in DataServices.GetUserById, it returns a User with correct name and email, but Id = 0.

Nonetheless, when the form is posted back, the model passed to the controller has the correct Id! It is contained in a hidden field. But where does it come from?

Here is part of the View:

@model CRUD_MVC.Models.User
*...*
<p>id of the user in Model : @Model.Id</ p>   *shows 0*
@Html.HiddenFor(model => model.Id)   *contains the correct Id!*

So my question is : why are there different values in the two Model.Id? And where does the "real" Id come from, since the only thing that was passed to the view is 0?

0 Answers0