Suppose I want to allow to select our entity (from a dropdown, etc) on
a page, let's say Product. As a result I may receive this:
public ActionResult SelectedAction(Guid productId)
{
}
But, I want to use model binders power, so instead I write model
binder to get my product from repository and instead use
public ActionResult SelectedAction(Product product)
{
if (ModelState.IsValid) {} else {}
}
My model binder will set model state to false if product is invalid.
Now, there're problems with this approach:
1. It's not always easy to use strongly-typed methods like
Html.ActionLink(c => c.SelectedAction(id)) since we need to pass
Product, not id.
2. It's not good to use entities as controller parameters, anyway.
3. If model state is invalid, and I want to redirect back and show
error, I can't preserve selected product! Because bound product is not
set and my id is not there. I'd like to do RedirectToAction(c =>
c.Redisplay(product)) but of course this is not possible.
I posted a solution here:
http://stackoverflow.com/questions/1453641/my-custom-asp-net-mvc-entity-binding-is-it-a-good-solution
Basically, it is to use EntityViewModel with both Id and Instance
properties:
public class EntityViewModel<T> where T : BaseEntity
{
public override string ToString()
{
return Id.ToString();
}
public Guid Id { get; set; }
public T Instance { get; set; }
}
Now, I double post it here because Sharp does already have its own
model binder which I think may be re-used for this or even integrated
with the presented approach. If it's bad, no problem, I'm not expert
in MVC/binders and can understand it ;-) If it's good, maybe somebody
find it good enough to integrated into Sharp.
Which may raise another question, it's that Sharp examples do not use
ViewModel technique but rather bind to entities themselves. This seems
to go well with scaffolding and "easy to use" but I rather see Sharp
as a well-designed collection of good and approved development
techniques. I would really like to see ViewModel and generic input
builders (
http://www.lostechies.com/blogs/jimmy_bogard/archive/
2009/04/24/how-we-do-mvc.aspx) integrated into Sharp Arch (though
input builders are part of MVC v2 and that's going to come, anyway).