I have classes like the following. That is many classes with the same few properties such as CreatedBy and ModifiedBy:
public class Test1 {
[DisplayName("Created By")]
public string CreatedBy { get; set; }
[DisplayName("Modified By")]
public string ModifiedBy { get; set; }
}
public class Test2 {
[DisplayName("Created By")]
public string CreatedBy { get; set; }
[DisplayName("Modified By")]
public string ModifiedBy { get; set; }
}
I would like to have a block of code that I reuse in different views for these classes. The block of the code should have formatting for the data such as:
<div class="a">
@Html.LabelFor(model => model.Note.CreatedBy)
@Html.TextBoxFor(model => model.Note.CreatedBy)
</div>
<div class="b">
@Html.LabelFor(model => model.Note.ModifiedBy)
@Html.TextBoxFor(model => model.Note.ModifiedBy)
</div>
I looked at a few different ways of doing this and initially was using a class to hold all the modified and created data. My solution was based upon this:
However now I have been told I cannot use a class as is used in this solution where the data is held in a class RowInfo. I must use fields directly as in the classes Test1 and Test2 I show above.
Can anyone suggest how I could arrange for the HTML code to be reused by more than one class. I understand I could use a few different ways but all that I know of seem to not allow me to share code between multiple classes that share the same fields.
I hope this makes sense. If not tell me and I will explain more.
You could define a base view model:
and then have the two similar view models derive from this base view model (as they are sharing common functionality):
Next you could define a custom editor template for the base view model (
~/Views/Shared/EditorTemplates/BaseViewModel.cshtml):As a side note you could also use an interface instead of an abstract class for the base model:
and have the editor template typed typed to this interface.
Then for your main view model:
you could invoke the custom editor template using the EditorFor helper: