0

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);
    }
5
  • 1
    I am not quite sure what you mean, but if you automatically want those properties populated you can use the constructor? Commented Jul 27, 2012 at 5:17
  • Your question is very unclear. Commented Jul 27, 2012 at 5:30
  • I mean how do i insert date from controller or model without having it to be inserted from view ? Commented Jul 27, 2012 at 6:49
  • Are you trying to post the model to an action then have the controller change the date? Commented Jul 27, 2012 at 6:58
  • No i just want to pass the current date as a hidden value so that user don't have to enter date field in the form. Thanks Commented Jul 27, 2012 at 7:03

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.