0


I have a question. I am new on ASP.NET MVC Code First.
I am creating a simple CRUD using Scaffold MVC.

My Model:

public class Manufacture
{
    [Key]
    public int ManufactureID { get; set; }

    [Required]
    [Column("Manufacture", TypeName = "varchar")]
    [MaxLength(25)]
    [Display(Name = "Manufacture")]
    public string ManufactureCode { get; set; }

    [Column("ManufactureDescription", TypeName = "varchar")]
    [MaxLength(50)]
    [Display(Name = "Description")]
    public string ManufactureDescription { get; set; }

    [Column("IsActive", TypeName = "bit")]
    [Display(Name = "Active?")]
    public bool IsActive { get; set; }

    public DateTime CreatedDateTime { get; set; }
}

My Controller:

public ActionResult ManufactureCreate()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ManufactureCreate([Bind(Include = "ManufactureID,ManufactureCode,ManufactureDescription,IsActive,CreatedDateTime")] Manufacture manufacture)
    {
        if (ModelState.IsValid)
        {
            if (db.Manufactures.Any(ac => ac.ManufactureCode.Equals(manufacture.ManufactureCode)))
             {
                return View();
            }
            else
            {
                db.Manufactures.Add(manufacture);
                db.SaveChanges();
                return RedirectToAction("ManufactureCreate");
            }
        }
        return View(manufacture);
    }

I want to add a value on "CreatedDateTime" field using current DateTime. When User click the "Save" button on the View. "CreatedDateTime" field will be filled by current DateTime.

How can I do that?
Please advise.
Thank you.

Haminteu
  • 1,292
  • 4
  • 23
  • 49
  • 2
    `manufacture.CreatedDateTime = DateTime.Now; db.Manufactures.Add(manufacture);` etc. But your editing data so always use a view model - [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Feb 26 '18 at 06:29

2 Answers2

1
manufacture.CreatedDateTime=DateTime.Now;

add above the line db.Manufactures.Add(manufacture);

Rick
  • 3,361
  • 1
  • 22
  • 29
Prathamesh
  • 36
  • 4
1

Modify your else block as below:

       else
            {
                manufacture.CreatedDateTime=DateTime.Now;
                db.Manufactures.Add(manufacture);
                db.SaveChanges();
                return RedirectToAction("ManufactureCreate");
            }

and yes, you should use ViewModel here as Stephen suggested in the comment.

Adnan Niloy
  • 469
  • 11
  • 18