2015-09-04 45 views
0

我想弄清楚爲什麼我的模型表的UserId列引用我的AspNetUsers表的主鍵「Id」(IdentityUser類IdentityModel )只顯示空值當我'創建()'條目。IdentityUser的外鍵引用顯示NULL值(EF6/ASP.NET MVC 5)

這裏是我的兩個)的代碼創建(在我的控制器類的ActionResult方法:

[Authorize] 
    public ActionResult Create() 
    { 
     ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname"); 
     return View(); 
    } 

    // POST: Expenses/Create 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    [Authorize] 
    public ActionResult Create([Bind(Include = "ID,Category,Description,GrossAmount,TaxAmount,NetAmount,Mileage,MileageRate,DateSubmitted,ExpenseDate,UserId")] Expense expense) 
    { 
     if (ModelState.IsValid) 
     { 
      expense.UserId = HttpContext.Current.User.Identity.Name; 
      db.Expenses.Add(expense); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname", expense.UserId); 
     return View(expense); 
    } 

這裏是我創建視圖代碼:

@{ 
    ViewBag.Title = "Create"; 
    Layout = "~/Views/Shared/_Layout.cshtml"; 

    DateTime today = DateTime.Today; 
    string formattedDate = today.ToString("MM/dd/yyyy"); 
} 

<h2>Create</h2> 

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 

    <div class="form-horizontal"> 
     <h4>Expense</h4> 
     <hr /> 
     @Html.ValidationSummary(true, "", new { @class = "text-danger" }) 

     <div class="form-group"> 
      @Html.LabelFor(model => model.UserId, htmlAttributes: new { @Value = user, @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.DateSubmitted, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.DateSubmitted, new { htmlAttributes = new { @Value = formattedDate, @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.DateSubmitted, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.ExpenseDate, htmlAttributes: new { @Value = @formattedDate, @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.ExpenseDate, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.ExpenseDate, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.DropDownListFor(model => model.Category, new SelectList(
        new List<String>{ 
         "Meals & Entertainment", 
         "Home Office", 
         "Travel", 
         "Phone", 
         "Auto - Mileage", 
         "Auto - Gas", 
         "Auto - Lease", 
         "Association Dues", 
         "Insurance Premium", 
         "Capital Assets", 
         "Trade Show & Promo", 
         "Pan Experience", 
         "Other" 
        }), new { @class = "form-control" }) 

       @Html.ValidationMessageFor(model => model.Category, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.Mileage, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.Mileage, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.Mileage, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.MileageRate, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.MileageRate, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.MileageRate, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.GrossAmount, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.GrossAmount, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.GrossAmount, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.TaxAmount, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.TaxAmount, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.TaxAmount, "", new { @class = "text-danger" }) 
      </div> 
     </div> 

     <div class="form-group"> 
      @Html.LabelFor(model => model.NetAmount, htmlAttributes: new { @class = "control-label col-md-2" }) 
      <div class="col-md-10"> 
       @Html.EditorFor(model => model.NetAmount, new { htmlAttributes = new { @class = "form-control" } }) 
       @Html.ValidationMessageFor(model => model.NetAmount, "", new { @class = "text-danger" }) 
      </div> 
     </div> 


     <div class="form-group"> 
      <div class="col-md-offset-2 col-md-10"> 
       <input type="submit" value="Create" class="btn btn-default" /> 
      </div> 
     </div> 
    </div> 
} 

<div> 
    @Html.ActionLink("Back to List", "Index") 
</div> 

@section scripts { 

    <script type="text/javascript"> 
     var province = 'bc'; 
     var grossAmount = document.getElementById('GrossAmount').value; 

     $(function() { 

      $('#ExpenseDate').datetimepicker({ 

       defaultDate: '@formattedDate', 

       format: 'L', 

       showClose: true, 

       showClear: true, 

       toolbarPlacement: 'top' 

      }); 

     }); 

     $('#DateSubmitted').prop('readonly', true); 
     $('#Mileage').prop('disabled', true); 
     $('#MileageRate').prop('disabled', true); 

     $(function() 
     { 
      $('#Category').on('change',function() 
      { 
       if ($(this).val() == 'Auto - Mileage') 
       { 
        $('#Mileage').prop('disabled', false); 
        $('#MileageRate').prop('disabled', false); 
       } 
       else 
       { 
        $('#Mileage').prop('disabled', true); 
        $('#MileageRate').prop('disabled', true); 
       } 

      } 

      ) 
     }) 


    </script> 
} 

如果你想看看我的模特班,你可以去這個帖子:


UPDATE:

感謝史蒂夫格林爲把我在正確的軌道上,並幫我更新的Create()方法是:

public ActionResult Create() 
    { 
     ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname"); 
     return View(); 
    } 

    // POST: Expenses/Create 

    [HttpPost] 
    [ValidateAntiForgeryToken] 
    [Authorize] 
    public ActionResult Create([Bind(Include = "ExpenseId,Category,Description,GrossAmount,TaxAmount,NetAmount,Mileage,MileageRate,DateSubmitted,ExpenseDate,UserId")] Expense expense) 
    { 
     if (ModelState.IsValid) 
     { 
      expense.UserId = System.Web.HttpContext.Current.User.Identity.Name; 
      db.Expenses.Add(expense); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     ViewBag.UserId = new SelectList(db.Users, "Id", "Fullname", expense.UserId); 

     foreach (ModelState modelState in ViewData.ModelState.Values) 
     { 
      foreach (ModelError error in modelState.Errors) 
      { 
       Response.Write(error); 
      } 
     } 
     Response.End(); 
     return View(expense); 

    } 

我現在沒有遇到任何重大錯誤,但是,現在ModelState.IsValid正在返回False,並且我輸入到Create.cshtml中的數據不是正在提交。

我添加一段代碼在Create()方法捉ModelState.Errors和它打印錯誤:System.Web.Mvc.ModelError。我也在Create()之前設置了一個斷點,當我檢查UserId的值時,我得到「null」。


最後更新:

我添加了一個字段,用戶ID的Create.cshtml看法,現在我得到的錯誤:INSERT語句衝突與外鍵約束「FK_dbo。 Expenses_dbo.AspNetUsers_ApplicationUser_Id」。衝突發生在數據庫「PacificPetExpenses」,表「dbo.AspNetUsers」,列'Id'。

要解決這個問題,我在我的控制器中修改了一些東西(請參閱下面的答案)。

謝謝。

+0

那麼你的費用對象在POST的頂部有一個UserId?可能需要查看用戶下拉的創建視圖代碼。確保它綁定回你的UserId字段。 –

+0

@SteveGreene我剛剛發佈了我的創建視圖代碼。 – Sicypher

+0

我在您的視圖中看不到UserId。您是否打算提供用戶選擇的下拉列表,或者您是否想要使用靜態用戶標識(例如登錄用戶)?我看到你在GET操作中建立了一個列表,但從不顯示它。 –

回答

0

裏面的內我的控制器的Create()方法,我有行:

expense.UserId = HttpContext.Current.User.Identity.Name; 

我成立了一個破發點和斷點就行了,它顯示了正確的UserId;但是,在執行完該行後,它會顯示用戶的電子郵件地址。

爲了解決這個問題我試圖改變上面的一行:

expense.UserId = System.Web.HttpContext.Current.User.Identity.GetUserId(); 

和支出雙雙被沒有錯誤提交,並顯示在它應該顯示的用戶提交的費用清單視圖!

1

如果不使用視圖的用戶ID,只需將它添加之前:

if (ModelState.IsValid) 
    { 
     expense.UserId = HttpContext.Current.User.Identity.Name; // or whatever 
     db.Expenses.Add(expense); 
     db.SaveChanges(); 
     return RedirectToAction("Index"); 
    } 

另一種常見的模式是添加一個隱藏字段的用戶名:

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken() 
    @Html.HiddenFor(model => model.UserId) <-- now it will post back 
    ... 

如果你想有一個下拉列表的用戶,這樣做:

[Authorize] 
public ActionResult Create() 
{ 
    ViewBag.UserList = new SelectList(db.Users, "Id", "Fullname"); 
    return View(); 
} 

然後在你的視圖中添加一個下拉列表的用戶:

<div class="form-group"> 
     @Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownListFor(model => model.UserId, Model.UserList, new { @class = "form-control" }) 
      @Html.ValidationMessageFor(model => model.UserId, "", new { @class = "text-danger" }) 
     </div> 
    </div> 
+0

謝謝你的幫助,但是,現在我得到一個錯誤,說:** INSERT語句與FOREIGN KEY約束「FK_dbo.Expenses_dbo.AspNetUsers_ApplicationUser_Id」衝突。衝突發生在數據庫「PacificPetExpenses」,表「dbo.AspNetUsers」,列'Id'。** – Sicypher

+0

用戶標識是否存在於數據庫中?在SaveChanges()之前檢查UserId的值,並確保Id在表AspNetUsers中。 –

+0

當我在Create()方法之前設置斷點時,UserId爲null,並且由於「ModelState」無效,因此Create()和SaveChanges()方法都不會執行。我添加了一段代碼來捕獲所有ModelState.Errors(請參閱上述問題中的更新),並捕獲System.Web.Mvc.ModelError的錯誤。 – Sicypher