0

I have a model that stores the identity of the current user who is creating the new record. How can I modify the ActionResult Create() to capture the current user's name and assign it to paCrtdBy?

Here is the model:

using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web;

namespace phaud.Models
{
public class phauds
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    [Required]
    [Display(Name = "Created By")]
    [MaxLength(128)]
    public string paCrtdBy { get; set; }

    private DateTime _createdOn = DateTime.Now;

    [Required]
    [Display(Name = "Record Date")]
    [DataType(DataType.DateTime)]
    public DateTime paCrtdDt {
        get
        {
            return (_createdOn == DateTime.MinValue) ? DateTime.Now : _createdOn;
        }
        set
        {
            _createdOn = value;
        }
     }
   }
 }

Here is the controller code for CREATE():

    // GET: phauds/Create
    public ActionResult Create()
    {           

        ViewBag.DropDownValues1 = new SelectList(new[] { 3, 6, 9 });
        ViewBag.DropDownValues2 = new SelectList(new[] { 9, 18, 27 });

        return View();
    }

    // POST: phauds/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,paCrtdBy,paCrtdDt,repId,callId,callDt,q_opClsCall,q_asstOffer,q_reassrCaller,q_empathy,q_prof,q_recap,q_deadAir,cmnts")] phauds phauds)
    {
        string userName = User.Identity.Name;
        //How do I assign the value of userName to the paCrtdBy field in the phauds.cs

        //How to assign DateTime.Now to paCrtdDt instead of doing it in the model

        if (ModelState.IsValid)
        {
            db.phauds.Add(phauds);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(phauds);
    }
user1916528
  • 379
  • 4
  • 23
  • 2
    The base controller has a [User Property](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.user?view=aspnetcore-2.1). Are you unaware of that property? [User Property](https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.user(v=vs.118).aspx#P:System.Web.Mvc.Controller.User) for MVC 6 (and previous). – Erik Philips Sep 05 '18 at 21:16
  • No, I'm just now learning. Thanks for the link, it's exactly what I needed! – user1916528 Sep 05 '18 at 21:19

0 Answers0