是否可以在不验证“子模型”的情况下验证MVC-3模型?

时间:2011-07-14 23:05:02

标签: c# validation asp.net-mvc-3

我有一个类需要指定另一个类,但我不希望MVC ModelState验证器检查辅助模型是否有效。这可能吗?

以下是简要概述:

我的实体看起来像这样:

public class WidgetType
{
    public long Id { get; private set; }

    [Required]
    public string Name { get; set; }

    ...
}

public class Widget
{
    public long Id { get; private set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public WidgetType WidgetType { get; set; }

    ...
}

我将它们封装在一个WidgetViewModel类中,我将这样传递给View,如下所示:

public class WidgetViewModel
{
    public Widget Widget { get; set; }

    public ICollection<WidgetType> WidgetTypes
    {
        get
        {
            return _repository.GetWidgets();
        }
    }

    ...
}

我的观点看起来像这样:

...
@Html.DropDownListFor( m => m.Widget.WidgetType.Id, new SelectList( new EquipmentViewModel().EquipmentTypes, "Id", "Name" ) )
...

除验证外,所有这些都有效。 ModelState.IsValid始终为false,因为"Widget.WidgetType.Name"是必需的。我需要用户选择WidgetType,但我不希望ModelState比“Widget.WidgetType.Id”更深入地验证(这应该是Widget对其外键所需的全部内容吗?)

有更好的方法吗?我觉得应该有一些方法来验证,而不是递归检查更深入的属性,但我找不到它。我错过了什么......?

3 个答案:

答案 0 :(得分:4)

public class WidgetViewModel
{    
    [Required]
    public string Name { get; set; }

    [Required]
    public WidgetType WidgetTypeId { get; set; }

    public SelectList WidgetTypes 
    {
        get
        {
             //This should be popuplated in your controller or factory not in the view model
             retun new SelectList{ _repository.GetWidgets(),"Id","Name");

        }
   }
}

在你看来

 @Html.DropDownListFor( m => m.WidgetTypeId, Model.WidgetTypes)

在您的控制器中

public ActionResult Create(WidgetViewModel model)
{
    Widget widget = new Widget{
         Name = model.Name,
         WidgetType = yourManager.GetWidgetTypeByID(model.WigetTypeId);
    };

    yourManager.Create(widget);

    //...
}

答案 1 :(得分:3)

如果您在视图中需要的只是WidgetID,那么您不需要在WidgetViewModel中包含整个Widget。只有拥有名为WidgetID的属性。视图模型类应该只包含视图所需的数据。

在提交表单时调用的控制器操作方法中,如果需要,可以使用WidgetID从数据库中获取Widget对象。

答案 2 :(得分:1)