Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Adding model with DateTime property results with default value (00001-01-01) in SQL Server

$
0
0

Hi guys,

I'm using ASP.NET Core 2.1 MVC. I have a Post model which has CreateDate property. I used input type="date" in View. When creating post after filling all inputs, it always addsDateTime property value as default (0001-01-01 00:00:00.0000000) though I pick various dates in DateTime field of the post creation form. The format in SQL is datetime2.    I also used attribute to format property. Here is the details to see:

In Post Model

public class Post
{
public int Id { get; set; }
[Required]
[MaxLength(55)]
public string Title { get; set; }

public string Image { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime CreatedDate { get; set; }

}

in ViewModel

public int Id { get; set; }
public Post Post { get; set; }

In View

<form method="post" asp-action="Postadd" asp-controller="Post" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly"></div>
<label asp-for="Post.Title" style="width: 45px">Title</label>
<input asp-for="Post.Title" class="postinput" type="text"><br>
<span asp-validation-for="Post.Title"></span><label asp-for="PostImage.FileName" >Upload Image</label>
<input asp-for="PostImage.FileName" class="forupload" type="file" name="file">
<label asp-for="Post.CreatedDate" style="width:80px">Start Date</label>
<input asp-for="Post.CreatedDate" class="postinput" type="date" name="date"><br>
<span asp-validation-for="Post.CreatedDate"></span>

</form>

Action

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Postadd(Post post, IFormFile file)
{
if (ModelState.IsValid)
{
if (file == null || file.Length == 0)
{
ModelState.AddModelError("", "No file selected");
return View();
}

string mypath = Path.Combine(_env.WebRootPath, "images", Path.GetFileName(file.FileName));

using (var stream = new FileStream(mypath, FileMode.Create))
{
await file.CopyToAsync(stream);
}

AdminPostModel postModel = new AdminPostModel();
postModel.Companies = await _offerDbContext.Companies.ToListAsync();

post.Image = file.FileName;
_offerDbContext.Posts.Add(post);
await _offerDbContext.SaveChangesAsync();
return RedirectToAction("Admin", "Admin");
}
else
{
ModelState.AddModelError("", "Couldn't create");
return View();
}

}

What is the problem?

(please focus on datetime parts of the code I provided, others I may share here incomplete, but ignore them as I know that they work).


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>