NibblyPig
NibblyPig

Reputation: 52922

Super simple MVC question, how does it know what the ID is of an object you're editing?

Having trouble grasping this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Movie movieToEdit)
{

    var originalMovie = (from m in _db.MovieSet
                         where m.Id == movieToEdit.Id
                         select m).First();

In this case you've posted your form, and it gets the movie you're going to edit by checking movieToEdit.Id

However I don't understand how it knows what the Id is. I thought that movieToEdit was created by examining the View. The fields on the View are only:

<fieldset>
    <legend>Fields</legend>
    <p>
        <label for="Title">Title:</label>
        <%= Html.TextBox("Title", Model.Title) %>
        <%= Html.ValidationMessage("Title", "*") %>
    </p>
    <p>
        <label for="Director">Director:</label>
        <%= Html.TextBox("Director", Model.Director) %>
        <%= Html.ValidationMessage("Director", "*") %>
    </p>
    <p>
        <label for="DateReleased">DateReleased:</label>
        <%= Html.TextBox("DateReleased", String.Format("{0:g}", Model.DateReleased)) %>
        <%= Html.ValidationMessage("DateReleased", "*") %>
    </p>
    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>

Presumably when you hit save it will construct the movieToEdit based on the textboxes on the page automatically. But Id isn't one of the fields on the page, so how does it know what it is? Does it create hidden fields for properties such as Id automatically?

Upvotes: 2

Views: 69

Answers (1)

Robert Koritnik
Robert Koritnik

Reputation: 105009

ID is most likely in your URL since default MVC route definition is:

{controller}/{action}/{id}

Your <form> in the view most likely posts back to something like:

http://www.yourappaddress.com/movies/edit/N

where N is movie ID. All other movie property values are sent via form POST values.

Upvotes: 1

Related Questions