WPF Data Templates Equivalent in ASP.NET MVC
WPF provides the ability to create data templates. These templates can be used to render objects of certain types. I have a list of objects within a hierarchy, that I wish to display in a view. An example of a single WPF data template is shown below. This renders the following control, containing a label and text box, when an object of type FreeTextQuestion is part of the model to be rendered onto the view.
<DataTemplate DataType="{x:Type QuestionTypes:FreeTextQuestion}">
<StackPanel x:Name="FieldTextQuestion">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200px"/>
<ColumnDefinition Width="20px"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label x:Name="label" Grid.Column="0" Content="{Binding Title}" Style="{StaticResource questionTitle}" />
<TextBox x:Name="textbox" Grid.Column="2" Style="{StaticResource standardTextBox}" src:FocusExtension.IsFocused="{Binding Path=IsFocused, Mode=TwoWay}" >
<TextBox.Text>
<Binding Path="Value" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<DataErrorValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
开发者_开发知识库 </TextBox>
</Grid>
</StackPanel>
</DataTemplate>
My question is how could I achieve this same thing in ASP.NET MVC? Is there such an Equivalent? Can this be achieved using Html Helper Extensions and/or user controls? There are dependencies, for example I might have a group box control which is the parent of the free text question control shown above, so some templates would contain a list of other templates, etc.
Any help greatly appreciated.
Many Thanks
The only way of doing that (that I know of) is using a strongly-typed partial view.
The equivalent is a ViewModel with DataAnnotation attributes.
Basically, instead of an XML document you create a class, and decorate the properties with attributes to specify the template and formatting information, and the validation constraints.
rsenna is correct that the representation of this model is through a strongly typed partial view, but the actual definition will occur in the view model class.
You will want to look into the ModelMetadata
, ModelMetadataProvider
, and ModelValidator
classes as well as their implemented derivatives and uses to get a full understanding of how this works.
The equivalents are editor and display templates, which are partial views placed in specially-named folders.
You can use @Html.DisplayFor()
or @Html.EditorFor()
to invoke these templates. The appropriate template will be picked based on the value you pass.
If no template exists, MVC will auto-generate one for you. As smartcaveman says, you can use data annotations to control to some extent what it auto-generates.
http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
精彩评论