使用在MVC中提交表单的用户标识更新数据库

时间:2014-09-13 10:16:34

标签: c# asp.net-mvc

我有一个用户可以创建新员工的表单。我想将userid存储在提交表单的数据库中。

这是我用于创建新条目的控制器:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Employee employee)
    {
        if (ModelState.IsValid)
        {
            db.Employee.Add(employee);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(employee);
    }

我有两张桌子。一个用于员工,另一个用于用户。正如您所见,我的员工表中有 UserID ,我想存储提交表单的用户ID。我可以在我的员工表中保存表单值,但无法获取用户标识。有什么想法吗?

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection")
    {
    }

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Employee> Employee { get; set; }
}

    [Table("UserProfile")]
     public class UserProfile
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }
}

[Table("Employee")]
public class Employee
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int EmployeeID { get; set; }
    public string EmployeeName { get; set; }
    public int DepartmentID { get; set; }
    public string Department { get; set; }
    public int UserId { get; set; }
 }

这是我的登录表单:

  <section id="loginForm">
  <h2>Use a local account to log in.</h2>
   @using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>Log in Form</legend>
    <ol>
        <li>
            @Html.LabelFor(m => m.UserName)
            @Html.TextBoxFor(m => m.UserName)
            @Html.ValidationMessageFor(m => m.UserName)
        </li>
        <li>
            @Html.LabelFor(m => m.Password)
            @Html.PasswordFor(m => m.Password)
            @Html.ValidationMessageFor(m => m.Password)
        </li>
        <li>
            @Html.CheckBoxFor(m => m.RememberMe)
            @Html.LabelFor(m => m.RememberMe, new { @class = "checkbox" })
        </li>
    </ol>
    <input type="submit" value="Log in" />
</fieldset>
  }
   </section>

1 个答案:

答案 0 :(得分:1)

你应该在下面试试这个。 我认为你错过了几件事情,你现在可以将它们与你自己的逻辑进行比较。

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Linq;
using System.Web;

class Program
{

    private static void Main(string[] args)
    {
        UsersContext context = new UsersContext();



        string currentUserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
        if (string.IsNullOrWhiteSpace(currentUserName))
        {
            currentUserName = HttpContext.Current.User.Identity.Name;
        }
        var currentUser = (from u in context.UserProfiles
                           where u.UserName.Equals(currentUserName)
                           select u).FirstOrDefault();

        if (currentUser != null)
        {
            context.Employee.Add(new Employee() { EmployeeName = "Mr. Codebased", UserID = currentUser.UserId });
            context.SaveChanges();

            var userProfile = context.Employee.Include("User").FirstOrDefault().User;
        }

    }

    public class UsersContext : DbContext
    {
        public UsersContext()
            : base()
        {
        }

        public DbSet<UserProfile> UserProfiles { get; set; }
        public DbSet<Employee> Employee { get; set; }
    }

    [Table("UserProfile")]
    public class UserProfile
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int UserId { get; set; }
        public string UserName { get; set; }
    }

    [Table("Employee")]
    public class Employee
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }

        public int UserID { get; set; }
        public UserProfile User { get; set; }
    }

}