Reputation: 1039
I have a base model class, NotificationBase, and two derived models, GeneralNotification and ReleaseNotification.
public class NotificationBase
{
public int Id { get; set; }
[Required]
[StringLength(50, ErrorMessage="Title must not exceed 50 characters.")]
public string Title { get; set; }
[Required(ErrorMessage="Type is required.")]
public int TypeId { get; set; }
[Required(ErrorMessage="Importance is required.")]
public int ImportanceId { get; set; }
public DateTime Created {get; set; }
[Required(ErrorMessage="Start date is required.")]
public DateTime StartDate { get; set; }
[Required(ErrorMessage="End date is required")]
public DateTime EndDate { get; set; }
[AllowHtml]
[Required(ErrorMessage="Details are required")]
public string Details { get; set; }
}
public class GeneralNotification : NotificationBase
{
[Required(ErrorMessage="Message is required.")]
[StringLength(50, ErrorMessage = "Message must be maximum 50 chararacters long.")]
public string Message { get; set; }
}
public class ReleaseNotification : NotificationBase
{
[Required(ErrorMessage="Version is required.")]
public string Version { get; set; }
}
I'm trying to use a single edit view to edit both derived notification types.
This view has a model of type NotificationBase.
The problem is I can't get the added properties of the derived types to be displayed in the edit view. Sending a model of the base type means I lose along the way the extra properties of the derived types.
Is there a workaround, or I just have to make separate views for each derived model ?
Upvotes: 7
Views: 3350
Reputation: 1039
Problem solved: I passed to the view a specific derived type model (GeneralNotification/ ReleaseNotification) instead of passing a base type model. The view stayed the same and everithing works now.
Upvotes: 0
Reputation: 49095
Set your model type to the base type:
@model NotificationBase
Then:
@Html.EditorForModel()
EditorForModel
is smart enough to render the form based on the concrete type passed on runtime.
Upvotes: 0
Reputation: 1040
This can also be solved by using an interface. For example if you want to avoid conditions in your views. Razor views can also be strongly typed with an interface.
You can go for a full interface implemented by NotificationBase with overrides in your derived classes. (note that NotificationBase would need to be abstract for this) Or you implement partial interfaces.
Kr
Upvotes: 0
Reputation: 56688
You can add a couple of conditions to your view. Suppose your view is strongly typed with base class:
@model NotificationBase
You can check for each subclass and add corresponding fields (untested code below!):
@if (Model is GeneralNotification)
{
Html.TextBoxFor(m => ((GeneralNotification) m).Message);
}
The same goes for second subtype of course:
@if (Model is ReleaseNotification)
{
Html.TextBoxFor(m => ((ReleaseNotification) m).Version);
}
Upvotes: 4