Reputation: 7838
I have a simple model for a contract:
public class Contract
{
public int Number { get; set; }
public DateTime DateSigned { get; set; }
}
When creating a new contract I'd like to automatically suggest the next available number. I get it from the database in my controller's Create action.
public Create()
{
ViewBag.SuggestNum = /* ... */;
return View();
}
In my View I have an EditorFor my Number and my DateSigned:
@Html.EditorFor( m => m.DateSigned )
@Html.EditorFor( m => m.Number )
I've tried both of these but they seem to have no effect whatsoever on the resulting html:
@Html.EditorFor( m => m.Number, new { @value = ViewBag.SuggestNum.ToString() } )
@Html.EditorFor( m => m.Number, new { @Value = ViewBag.SuggestNum.ToString() } )
Another option is to construct a Contract object in my controller but then my non-nullable DateTime property's editor defaults to 01.01.0001 instead of being empty:
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 });
}
So this doesn't work either.
Any ideas how to set the value of my Number property's editor but not my DateSigned's?
Upvotes: 1
Views: 1585
Reputation: 1038710
You could make the DateSigned
property a Nullable<DateTime>
:
public class Contract
{
public int Number { get; set; }
[Required]
public DateTime? DateSigned { get; set; }
}
and then in your controller:
public ActionResult Create()
{
var suggestNum = ... fetch from db
return View( new Contract() { Number = suggestNum });
}
and in your view:
@Html.EditorFor( m => m.DateSigned )
@Html.EditorFor( m => m.Number )
Upvotes: 1