Łukasz W.
Łukasz W.

Reputation: 9755

How MVC fill Id parameter?

today I've got some interesting observation, that I need to explain. I've got my Person class that is described as above:

public class Person
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
}

now in my MVC2 application I've got PersonController with following edit metod:

public ActionResult Edit(int id)
{
    var permission = _service.GetPerson(id);
    return View(person);
}

[HttpPost]
public ActionResult Edit(Person person)
{
    if (ModelState.IsValid)
    {
        _service.UpdatePerson(permission);
        return RedirectToAction("Index");
    }

    return View(person);
}

Now on my Edit.aspx view I have form that contains only FirstName and LastName, but what suprise me when the post is done in my controller the Person object have an Id setted correctly (which was not part of a form).

Now I guess that it's taken from the rout value of an id parameter, that is send in my action address, but is it save? I mean.. It's nice that I do not have to put hidden field for id, but is there any danger caused by mixing get and post parameters in mvc2?

And one more concern. What if I do put hidden for id. Then it will be sent both ways (get and post), so then.. which id will be used?

Upvotes: 1

Views: 656

Answers (2)

Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17794

when mvc default model binder binds objects it looks for its values in many places and matched route is one of those places. if u change ur property name from id to personID it will not get populated from route value and u have to put hidden field in ur form to get it there. to avoid such confusion i always name properties different from route parameters.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039348

Yes it is taken from the route. It is dangerous because if you rename this property on the Person class your code might break. Also if you change the route the same might happen.

And to answer your second question. Assume the following form:

<form action="/home/edit/5" method="post">
    <input type="text" name="Id" value="1" />
    <input type="submit" value="Go" />
</form>

In this case the Id will be taken from the POST request and not the route.

Upvotes: 2

Related Questions