Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC a better way to post model ID?

I have a ViewModel I am binding to a view:

ProductViewModel model = Mapper.Map<Product, ProductViewModel>(product);
return View(model);

The view (and viewmodel) is used to edit a Product so ProductViewModel has an ID property that corresponds to the ID in the database.

And to Post the ID back to the Controller I am doing this in my form on the view:

@Html.HiddenFor(x => x.Id)

Even though this works - I was wondering whether there was a better way to Post the ID back to the Controller? Route Values maybe? or is this a fairly standard pattern/approach?

like image 866
Greg Avatar asked Jun 22 '12 13:06

Greg


1 Answers

If I have a GET action that includes the id in my route: /Products/Edit/1 then I usually keep it as a route value:

[HttpPost]
public ActionResult Edit(int id, EditProductViewModel model)

This is purely a preference of mine, though. There is no right or wrong way to do it.

The nice thing about this method is you no longer need to pass it in using a Hidden value since it is part of the URL. Actually, if you do pass it in with a Hidden value I believe it will be ignored.

Alternatively, since id is part of the route, you don't even need to have a separate parameter:

[HttpPost]
public ActionResult Edit(EditProductViewModel model)

public class EditProductViewModel 
{
    public int Id { get; set; }
}

Again, this is purely a preference thing.

like image 144
Dismissile Avatar answered Oct 02 '22 13:10

Dismissile