Html.Editor not rendering the value

跟風遠走 提交于 2019-12-02 07:22:45

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!