Input box as “date” on web when model is “int”

2019-09-21 11:09发布

问题:

I am using ASP.NET Core v2 and Razorpages

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)

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

<input asp-for="@Model.AgrRow.FrDt" class="form-control" />

MODEL

[DataType(DataType.Date)]
public int FrDt { get; set; }

My intention was to convert the value entered on the webpage to an int like this:

CS PAGE

AgrRow.FrDt = int.Parse(AgrRow.FrDt.ToString("yyyyMMdd"));

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: I am using Chrome and the built in date picker

How can I resolve this issue?

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());
}

回答1:

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.

View Model:

class AgrRowVM
{
  public DateTime? FrDt {get; set;}
  //Rest of the properties
}

Model:

class AgrRow
{
  public int? FrDt {get; set;}
  //Rest of the properties
} 

After posting values to serverside map View Model to Orginal model.

if(agrRowVMObj.FrDt.HasValue)
{
  agrRowObj.FrDt = int.Parse(agrRowVMObj.FrDt.ToString("yyyyMMdd"));
}