我想弄清楚为什么我的模型表的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操作中建立了一个列表,但从不显示它。 –