Suppose I have ViewModel like
public class AnotherViewModel
{
public string Name { get; set; }
}
public class MyViewModel
{
public string Name { get; set; }
public AnotherViewModel Child { get; set; }
public AnotherViewModel Child2 { get; set; }
}
In the view I can render a partial with
<% Html.RenderPartial("AnotherViewModelControl", Model.Child) %>
In the partial I'll do
<%= Html.TextBox("Name", Model.Name) %>
or
<%= Html.TextBoxFor(x => x.Name) %>
However, the problem is that both will render name="Name" while I need to have name="Child.Name" in order for model binder to work properly. Or, name="Child2.Name" when I render the second property using the same partial view.
How do I make my partial view automatically recognize the required prefix? I can pass it as a parameter but this is too inconvenient. This is even worse when I want for example to render it recursively. Is there a way to render partial views with a prefix, or, even better, with automatic reconition of the calling lambda expression so that
<% Html.RenderPartial("AnotherViewModelControl", Model.Child) %>
will automatically add correct "Child." prefix to the generated name/id strings?
I can accept any solution, including 3-rd party view engines and libraries - I actually use Spark View Engine (I "solve" the problem using its macros) and MvcContrib, but did not find a solution there. XForms, InputBuilder, MVC v2 - any tool/insight that provide this functionality will be great.
Currently I think about coding this myself but it seems like a waste of time, I can't believe this trivial stuff is not implemented already.
A lot of manual solutions may exists, and all of them are welcome. For example, I can force my partials to be based off IPartialViewModel<T> { public string Prefix; T Model; }. But I'd rather prefer some existing/approved solution.
UPDATE: there's a similar question with no answer here.
Like you, I add Prefix property (a string) to my ViewModels which I append before my model bound input names. (YAGNI preventing the below)
A more elegant solution might be a base view model that has this property and some HtmlHelpers that check if the view model derives from this base and if so append the prefix to the input name.
Hope that helps,
Dan
How about just before you call RenderPartial you do
Then in your partial you have
You can extend Html helper class by this :
and simply use it in your views like this :
and you will see everything is ok!
Using MVC2 you can achieve this.
Here is the strongly typed view:
Here is the strongly typed view for the child class (which must be stored in a subfolder of the view directory called EditorTemplates):
Here is the controller:
Here are the custom classes:
And the output source:
Now this is complete. Set a breakpoint in the Create Post controller action to verify. Don't use this with lists however because it wont work. See my question on using EditorTemplates with IEnumerable for more on that.