我想弄清楚爲什麼我的模型表的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'。
要解決這個問題,我在我的控制器中修改了一些東西(請參閱下面的答案)。
謝謝。
那麼你的費用對象在POST的頂部有一個UserId?可能需要查看用戶下拉的創建視圖代碼。確保它綁定回你的UserId字段。 –
@SteveGreene我剛剛發佈了我的創建視圖代碼。 – Sicypher
我在您的視圖中看不到UserId。您是否打算提供用戶選擇的下拉列表,或者您是否想要使用靜態用戶標識(例如登錄用戶)?我看到你在GET操作中建立了一個列表,但從不顯示它。 –