【发布时间】:2017-06-16 11:44:10
【问题描述】:
所以我有一个客户模型,它需要与 AspNetUsers 建立一对零或一的关系。我希望这个工作的方式是让用户注册。然后,如果他们愿意,请转到 example.com/Customers/Create 并创建一个客户记录,他们可以编辑或删除该记录。一个用户只能有一个或零个客户记录。
他们的问题是,当用户创建了客户时,客户视图为用户提供了创建另一个客户的选项,如果他这样做了,就会发生错误。
如何防止这种情况发生?如果用户已经在此处创建了客户,则不应自动为他们提供创建客户的选项:
我还必须阻止这个服务器端。
型号:
public class Customer
{
public int CustomerID { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public string Name { get; set; }
}
OnModelCreating:
modelBuilder.Entity<ApplicationUser>()
.HasOptional(m => m.Customer)
.WithRequired(m => m.ApplicationUser)
.Map(p => p.MapKey("UserId"))
在控制器上创建方法(POST)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CustomerID,Name")] Customer customer)
{
if (ModelState.IsValid)
{
UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var CurrentUser = UserManager.FindById(User.Identity.GetUserId());
customer.ApplicationUser = CurrentUser;
db.Customers.Add(customer);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(customer);
}
当用户创建客户并在创建视图中阻止任何人再创建时,我应该在我的索引视图中更改哪些不是“创建新”选项。
索引:
@model IEnumerable<WebApplication8.Models.Customer>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.CustomerID }) |
@Html.ActionLink("Details", "Details", new { id=item.CustomerID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.CustomerID })
</td>
</tr>
}
</table>
创建视图:
@model WebApplication8.Models.Customer
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Customer</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Name, "", 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 {
@Scripts.Render("~/bundles/jqueryval")
}
【问题讨论】:
标签: html asp.net-mvc razor