对派生的mvc模型使用单一视图 [英] Using a single view for derived mvc models
问题描述
我有一个基本模型类NotificationBase和两个派生模型GeneralNotification和ReleaseNotification.
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.
此视图具有NotificationBase类型的模型.
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 ?
推荐答案
您可以在视图中添加几个条件.假设您的视图是使用基类强类型化的:
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);
}
这篇关于对派生的mvc模型使用单一视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!