Binding, Prefixes and generated HTML
Posted
by Vman
on Stack Overflow
See other posts from Stack Overflow
or by Vman
Published on 2010-03-23T01:44:53Z
Indexed on
2010/03/23
1:51 UTC
Read the original article
Hit count: 301
MVC newbie question re binders. Supposing I have two strongly typed partial actions that happen to have a model attributes with the same name, and are rendered in the same containing page i.e.:
Class Friend {string Name {get; set ;} DateTime DOB {get; set ;}}
Class Foe {string Name {get; set ;} string ReasonForDislike {get; set ;}}
Both partials will have a line:
<%= Html.TextBoxFor(model => model.Name) %>
And associated controller actions:
public ActionResult SaveFriend(Friend friend)
public ActionResult SaveFoe(Foe foe)
My problem is that both will render on my containing page with the same id (of course, bad for lots of reasons). I’m aware of the [Bind] attribute that allows me add a prefix, resulting in code:
public ActionResult SaveFriend([Bind(Prefix = “friend”)] Friend friend)
<%= Html.TextBox("friend.Name", Model. Name) %> //Boo, no TextBoxFor :(
But this still doesn’t cut it. I can just about tolerate the loss of the strongly typed TextBoxFor helpers but I’ve yet to get clientside validation to work with prefixes: I’ve tried:
<%= Html.ValidationMessage("friend.Name") %>
...and every other variant I can think of.
I seem to need the model to be aware of the prefix in both directions but bind only applies when mapping the inbound request. It seems (to me) a common scenario but I’m struggling to find examples out there. What am I missing!
Thanks in advance.
© Stack Overflow or respective owner