ktm
ktm

Reputation: 6085

Entering data from asp.net mvc

I would like to automatically insert username, userid, date such thing from (server side) model in asp.net mvc how do i insert in such model ?

public class Enquiry
{
    public int ID { get; set; }
    public DateTime Date { get; set; }
    [Required]
    public string Name { get; set; }
    public string Contactno { get; set; }
    public string Remarks { get; set; }
    public string UserId { get; set; }
    public string UserName { get; set; }
    public string Editdate { get; set; }
    public string status { get; set; }


}

public class EnquiryDBContext : DbContext
{
    public DbSet<Enquiry> Enquiries { get; set; }

}

How do i insert date from controller or model without having it to be inserted from view ?

my controller is like this

    [HttpPost]
    public ActionResult Create(Enquiry enquiry)
    {
        if (ModelState.IsValid)
        {

            db.Enquiries.Add(enquiry);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(enquiry);
    }

Upvotes: 0

Views: 126

Answers (1)

jim tollan
jim tollan

Reputation: 22485

ktm,

just populate the date in the HttpGet action and then pass that to the view. here's a snippet:

Controller:

[HttpGet]
public ActionResult Create()
{
    Enquiry enquiry = new Enquiry();
    enquiry.Date = DateTime.UtcNow;
    // set any other required properties
    return View(enquiry);
}

in your create view:

// ref to base model
@model yournamespace.Models.Enquiry

// add the date from the controller as a hidden field
@Html.HiddenFor(m => m.Date)
<!-- other properties -->

then, just use your HttpPost actionmethod as before -voila!

Upvotes: 2

Related Questions