在视图中,我正在显示日期列bcp,当前它默认为'1900-01-01'。 当bcp ='1900-01-01'时在视图中如何在Editorfor中显示空值?
型号:
public partial class Training_test
{
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
public System.DateTime bcp { get; set; }
}
查看:
@Html.EditorFor(model => model.bcp, new { htmlAttributes = new { @class = " datepicker" } })
SQL脚本:
CREATE TABLE Training_test(
[cart_id] [int] IDENTITY(1,1) NOT NULL,
[bcp] [date] NOT NULL CONSTRAINT [DF_TrainingChecklist_bcp_1_test] DEFAULT ('1900-01-01'),
答案 0 :(得分:0)
为什么不遵循这些原则,根据您的bcp值创建一个计算变量? 看起来应该像这样:
//in your class
public DateTime BcpStr => bcp.equals(new DateTime(1900,1,1) ? null : bcp;
//in your view
@Html.EditorFor(model => model.BcpStr , new { htmlAttributes = new { @class = " datepicker" } })
答案 1 :(得分:0)
对于Training_test类(我认为是模型类,它将映射到SQL表),您需要一个 ViewModel 。 在ViewModel类中,您必须在将bcp属性从模型映射到ViewModel 时执行所需的逻辑。
例如:
public class ViewModel
{
//you can use DateTime type like your model
public string bcp { get; set; }
}
在您的控制器中:
Training_test result = GetYourDataFromDB(); //retrieve your model data from db
//viewModel acts like a data transfer object and you can apply any formatting
//after the query and before sending the data back to the view
var viewModel = new ViewModel
{
bcp = result.bcp == DateTime.Parse("1900-1-1") ? null :
result.bcp.ToString()
};
return View(viewModel);
,并在您的视图中(只需确保将视图中的@model类型分配给 ViewModel类):
@Html.EditorFor(model => model.bcp, new { htmlAttributes = new { @class = " datepicker" } })
希望有帮助。