输入框为“日期”在网络上,当模型为“ int”时 [英] Input box as "date" on web when model is "int"
问题描述
我正在使用ASP.NET Core v2和Razorpages
I am using ASP.NET Core v2 and Razorpages
在SQL(和模型)中,我有一个字段 [FrDt]
数据类型 int,我需要在其中存储日期值(以int形式)(我无法在SQL中更改数据类型)
In SQL (and in the model) I have a field [FrDt]
of data type "int" where I need to store a date value (as int) (I can't change the data type in SQL)
如果在模型中设置 [DataType(DataType.Date)]
,则会自动在网络上获取输入的日期类型。但是当我提交时,这些值不会发送到服务器。可能是因为该值的类型为date并且字段为int
If I set [DataType(DataType.Date)]
in the model I automatially get an input "date" type on web. but when I submit, the values are not sent to the server. probably because the value is of type date and the field is int
RAZORPAGE
RAZORPAGE
<input asp-for="@Model.AgrRow.FrDt" class="form-control" />
模型
[DataType(DataType.Date)]
public int FrDt { get; set; }
我的意图是将在网页上输入的值转换为如下所示的int值:
My intention was to convert the value entered on the webpage to an int like this:
CS页面
AgrRow.FrDt = int.Parse(AgrRow.FrDt.ToString("yyyyMMdd"));
但是输入的日期值不会发送到服务器,而是发送0(零),因此解析不起作用。如果我从模型中删除[DataType(DataType.Date)],则会在网络上看到一个普通的输入框,并将输入的值发送到服务器。
But the date value entered is not sent to the server, instead 0 (zero) is sent so the parse do not work. If I remove the [DataType(DataType.Date)] from the model I get a normal inputbox on web and the value I enter is sent to the server.
btw:我正在使用Chrome和内置的日期选择器
btw: I am using Chrome and the built in date picker
如何解决此问题?
更新-Post方法返回0,可能是因为SQL中的默认值为零
UPDATE - Post Method Returns 0, probably because the default value in SQL is zero
public async Task<IActionResult> OnPostSaveNewRowAsync() {
Console.WriteLine("FRDT = " + AgrRow.FrDt.ToString());
}
推荐答案
使用视图模型绑定视图而不是实际模型,它将包含DateTime类型的属性。然后将视图模型映射到实际的实体模型。
Use View Model to bind view instead of actual model, which will contain DateTime type of property. Then Map View Model to actual Entity Model.
视图模型:
class AgrRowVM
{
public DateTime? FrDt {get; set;}
//Rest of the properties
}
型号:
class AgrRow
{
public int? FrDt {get; set;}
//Rest of the properties
}
发布值后
if(agrRowVMObj.FrDt.HasValue)
{
agrRowObj.FrDt = int.Parse(agrRowVMObj.FrDt.ToString("yyyyMMdd"));
}
这篇关于输入框为“日期”在网络上,当模型为“ int”时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!