Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

c# - Input box as "date" on web when model is "int"

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

enter image description here

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());
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...