I'm having problems making the Html.Editor rendering the desire HTML.
Here is the scenario:
// assign the value
ViewBag.BeginDate = seaBeginEnd.beginDate;
//View
@Html.Editor("Begin", ViewBag.BeginDate as DateTime?)
//HTML Source
<div class="editor-field">
<input class="text-box single-line" id="Begin" name="Begin" type="text" value="" />
</div>
I was specking to see a value of 1/19/2011 12:00:00 AM which is the value of ViewBag.BeginDate, any insights.
Thanks for your help!
I was specking to see a value of 1/19/2011 12:00:00 AM which is the value of ViewBag.BeginDate
You cannot expect such thing by passing Begin
as first parameter to the Html.Editor
helper. The second parameter doesn't do what you think it does. It simply sends some additional view data to the editor template but the original value you are binding to is called Begin
so that's what you should assign a value to. Like this:
public ActionResult Index()
{
ViewBag.Begin = DateTime.Now;
return View();
}
and then:
@Html.Editor("Begin")
Obviously every time I see someone using ViewBag/ViewData and not strongly typed helpers I feel in the obligation to recommend view models and strongly typed helpers. Example:
Model:
public class MyViewModel
{
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime Date { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Date = DateTime.Now
});
}
}
and the corresponding strongly typed view:
@model AppName.Models.MyViewModel
@Html.EditorFor(x => x.Date)