2016-05-10 5 views
2

私はMVC5の新機能で、小さなリストアプリケーションを作成しようとしています。私は、ユーザー名とパスワードを持つUserLoginテーブルと、そのユーザーに関する他のすべての情報を含むUserProfileテーブルを作成しました。これらのテーブルと相関関係のある機能は正常に動作しています。ユーザーは登録、ログイン、ログアウトができ、該当するテーブルが更新されます。外部キーからuserprofileテーブルへ参照されるテーブルの項目のリストを表示

私はまた、ユーザーが追加したいアイテムを持つdo do listテーブルを持っています。これは私が困っているところです。特定のユーザーを参照する方法とそのユーザーに固有のtodolistテーブル情報を表示する方法を理解できません。

アカウント・コントローラ:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using ToDoListApplicationNew.Models.DB; 
using ToDoListApplicationNew.Models.ViewModel; 

namespace MyToDoListApplication.Models.EntityManager 
{ 
    public class UserProfileManager 
    { 
     public void AddUserAccount(UserSignUp newUser) 
     { 
      // create database connection 
      using (ToDoDBEntities db = new ToDoDBEntities()) 
      { 
       // Collect viewmodel data 
       // Here building goes by object type and not foregin key relationship 
       UserLogin UL = new UserLogin(); 
       UL.Username = newUser.Username; 
       UL.Password = newUser.Password; 

       // Add the UserLogin object I just built to the database 
       db.UserLogins.Add(UL); 
       db.SaveChanges(); 

       UserProfile UP = new UserProfile(); 
       // establish connection to UL by establishing foreign key relationship 
       UP.UserLoginID = UL.UserLoginID; 
       // Now add the new table properties to the new object 
       UP.FirstName = newUser.FirstName; 
       UP.LastName = newUser.LastName; 
       UP.CreationDate = newUser.CreationDate; 
       UP.Email = newUser.Email; 

       // Add UserProfile object to databse and save changes 
       db.UserProfiles.Add(UP); 
       db.SaveChanges(); 
      } 
     } 

     //Check if user is real before login is allowed 
     public bool isLoginReal(string LoginName) 
     { 
      using (ToDoDBEntities DB = new ToDoDBEntities()) 
      { 
       // Return the user from the DB whose login name matches the LoginName string passed in as perameter 
       return DB.UserLogins.Where(o => o.Username.Equals(LoginName)).Any(); 
      } 
     } 

     // Check if password exists 
     public string GetUserPassword(string loginName) 
     { 
      using (ToDoDBEntities db = new ToDoDBEntities()) 
      { 
       // retrieves user by comparing the username to the loginname passed in as a perameter 
       var user = db.UserLogins.Where(o => o.Username.ToLower().Equals(loginName)); 
       if (user.Any()) 
        return user.FirstOrDefault().Password; 
       else 
        return string.Empty; 
      } 
     } 
    } 
} 

はここに私のUSERHOME図である:

using MyToDoListApplication.Models.EntityManager; 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using System.Web.Security; 
using ToDoListApplicationNew.Models.DB; 
using ToDoListApplicationNew.Models.ViewModel; 

namespace ToDoListApplicationNew.Controllers 
{ 
    public class AccountController : Controller 
    { 
     // GET: Account 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     #region signup methods 
     // Get method for signup page 
     public ActionResult SignUpPage() 
     { 
      return View(); 
     } 

     // Post method for signup page - post to db 
     [HttpPost] 
     // Pass in the UserSign up model object to be built 
     public ActionResult SignUpPage(UserSignUp USUV) 
     { 
      // Form is filled out and then method is entered 
      if (ModelState.IsValid) 
      { 
       // Form is filled out and database connection is established if form is valid 
       UserProfileManager UPM = new UserProfileManager(); 

       if (!UPM.isLoginReal(USUV.Username)) 
       { 
        // data access . adduseraccount from entity manager (where model objects are built) 
        UPM.AddUserAccount(USUV); 
        FormsAuthentication.SetAuthCookie(USUV.FirstName, false); 
        return RedirectToAction("Welcome", "Home"); 
       } 
       else 
       { 

       } 
      } 
      return View(); 
     } 
     #endregion 

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

     [HttpPost] 
     public ActionResult Login(UserLoginView ULV, string returnURL) 
     { 
      if(ModelState.IsValid) 
      { 
       UserProfileManager UPM = new UserProfileManager(); 
       //retrive the password using the GetUserPassword() from UserProfileManager 
       // This will pass the user name to the gup method and if the username and password exist 
       // it will redirect the user to the welcome page. 
       string password = UPM.GetUserPassword(ULV.Username); 

       // If password is wrong or blank, catch with error message to user 
       if(string.IsNullOrEmpty(password)) 
       { 
        ModelState.AddModelError("", "The user login or password provided is incorrect"); 
       } 
       else 
       { 
        if(ULV.Password.Equals(password)) 
        { 
         FormsAuthentication.SetAuthCookie(ULV.Username, false); 
         return RedirectToAction("_UserHome", "Account"); 
        } 
        else 
        { 
         ModelState.AddModelError("", "The password provided is incorrect"); 
        } 
       } 
      } 
      return View(); 
     } 

     [Authorize] 
     public ActionResult SignOut() 
     { 
      FormsAuthentication.SignOut(); 
      return RedirectToAction("Index", "Home"); 
     } 

     #region UserHome 
     // After Login User is redirected to the _UserHome.cshtml view 
     // This is where listItems should be showing up 
     // MyList viewModel 
     public ActionResult UserHome() 
     { 
      if (Session["UserLoginID"] != null) 
      { 
       using (ToDoDBEntities db = new ToDoDBEntities()) 
       { 
        return View(db.MyListItems.ToList()); 
       } 
      } 
      else 
      { 
       return RedirectToAction("LogIn"); 
      } 
     } 

     #endregion 
    } 
} 

は、ここに私のエンティティの接続を管理するための私のクラスです。私は何をしようとしていますが、彼または彼女がログインすると、ユーザーはここにリダイレクトされており、彼らのこのページにリスト表示を行うための

@model IEnumerable<ToDoListApplicationNew.Models.DB.MyListItem> 

@{ 
    ViewBag.Title = "UserHome"; 
} 

<h2>UserHome</h2> 

<p> 
    @Html.ActionLink("Create New", "Create") 
</p> 
<table class="table"> 
    <tr> 
     <th> 
      @Html.DisplayNameFor(model => model.ItemDate) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.Item) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.ItemImportance) 
     </th> 
     <th> 
      @Html.DisplayNameFor(model => model.UserProfile.FirstName) 
     </th> 
     <th></th> 
    </tr> 

@foreach (var item in Model) { 
    <tr> 
     <td> 
      @Html.DisplayFor(modelItem => item.ItemDate) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.Item) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.ItemImportance) 
     </td> 
     <td> 
      @Html.DisplayFor(modelItem => item.UserProfile.FirstName) 
     </td> 
     <td> 
      @Html.ActionLink("Edit", "Edit", new { id=item.MyToDoListID }) | 
      @Html.ActionLink("Details", "Details", new { id=item.MyToDoListID }) | 
      @Html.ActionLink("Delete", "Delete", new { id=item.MyToDoListID }) 
     </td> 
    </tr> 
} 

</table> 

を持っている私はまた、データベース設計の画像を添付しています。 enter image description here

私のログインとサインアップの機能は素晴らしいです。私はもともと、彼らは本質的にハイユーザー、歓迎を言った "ようこそ"ページにリダイレクトされました。しかし、これは私がログインをテストしている間だけだった。今、私はリスト項目を行うためにこの3番目のテーブルを追加しました。私はedmxを更新しました。また、私は現在、私はしかし、私はこれを行う方法のアイデアを持っていたとき(私はそれを構築し使用していないこののviewmodelています

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.ComponentModel.DataAnnotations; 

namespace ToDoListApplicationNew.Models.ViewModel 
{ 
    public class userListViewModel 
    { 
     [Key] 
     public int MyToDoListID { get; set; } 

     public int UserProfileID { get; set; } 

     [DataType(DataType.DateTime)] 
     [Display(Name =" Date of input")] 
     public DateTime ItemDate { get; set; } 

     [Required(ErrorMessage = "*")] 
     [Display(Name ="New Item")] 
     public string Item { get; set; } 

     [Required(ErrorMessage = "*")] 
     [Display(Name ="Importance level (1 - 10")] 
     public int ItemImportance { get; set; } 
    } 
} 

は、私は任意の助けを本当に感謝意味をなさないdoesntの何かが私を聞かせてください場合。知っていると私はそれを私ができる最善を説明しよう

乾杯を、

答えて

0

あなたのuserListViewModelクラスに、このナビゲーションプロパティを追加する必要があります。目の後

public UserProfile UserProfile{ get; set;} 

ビューは動作するはずです(cshtmlファイル)。

ただし、EntityFrameworkを使用しているとすると、ナビゲーションプロパティが空である可能性があります。 UserHomeアクションを次のように変更してみてください。

public ActionResult UserHome() 
{ 
    if (Session["UserLoginID"] != null) 
    { 
     using (ToDoDBEntities db = new ToDoDBEntities()) 
     { 
      // Include fetches the data behind navigation properties 
      return View(db.MyListItems.Include(x => x.UserProfiles).ToList()); 
     } 
    } 
    else 
    { 
     return RedirectToAction("LogIn"); 
    } 
} 
関連する問題