ASP .NET MVC 3中模型的ONE属性的默认值

时间:2012-02-15 13:52:19

标签: c# asp.net-mvc-3 html-helper

我有一个简单的合同模型:

public class Contract
{
    public int Number { get; set; }
    public DateTime DateSigned { get; set; }
}

创建新合约时,我想自动建议下一个可用的号码。我在控制器的Create操作中从数据库中获取它。

public Create()
{
    ViewBag.SuggestNum = /* ... */;
    return View();
}

在我的视图中,我有一个EditorFor my Number和我的DateSigned:

@Html.EditorFor( m => m.DateSigned )
@Html.EditorFor( m => m.Number )

我已尝试过这两种方法,但它们似乎对生成的html没有任何影响:

@Html.EditorFor( m => m.Number, new { @value = ViewBag.SuggestNum.ToString() } ) 
@Html.EditorFor( m => m.Number, new { @Value = ViewBag.SuggestNum.ToString() } )

另一种选择是在我的控制器中构造一个Contract对象,但是我的不可为空的DateTime属性的编辑器默认为01.01.0001而不是为空:

public Create()
{
    var SuggestNum = /* ... */;

    // The new object has a DateSigned property with the default value of 01.01.0001
    return View( new Contract() { Number = SuggestNum }); 
}

所以这也不起作用。

如何设置我的Number属性编辑器的值而不是我的DateSigned的值?

1 个答案:

答案 0 :(得分:1)

您可以将DateSigned属性设为Nullable<DateTime>

public class Contract
{
    public int Number { get; set; }

    [Required]
    public DateTime? DateSigned { get; set; }
}

然后在你的控制器中:

public ActionResult Create()
{
    var suggestNum = ... fetch from db
    return View( new Contract() { Number = suggestNum }); 
}

并在您看来:

@Html.EditorFor( m => m.DateSigned )
@Html.EditorFor( m => m.Number )