2015-09-04 46 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