我有以下型号:
public class Expense
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
[Column(TypeName = "Money")]
public decimal Limit { get; set; }
[Required]
[ForeignKey("UserProfile")]
public int UserProfileId { get; set; }
[Required]
public virtual UserProfile UserProfile { get; set; }
}
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public virtual ICollection<Expense> Expenses { get; set; }
}
我有一个登录用户,我希望该用户能够添加新的费用。创建控制器操作如下所示:
//
// GET: /Expenses/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Expenses/Create
[HttpPost]
public ActionResult Create(Expense expense)
{
if (ModelState.IsValid)
{
UserProfile user = db.UserProfiles.Single(u => u.UserName == User.Identity.Name)
user.Expenses.Add(expense);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(expense);
}
有观点:
@model MoneyDrainPlug.Models.Expense
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Expense</legend>
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Limit)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Limit)
@Html.ValidationMessageFor(model => model.Limit)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
当帖子发生时,控制器中的 ModelState.IsValid 为 false。这是因为费用中没有设置 UserProfileId。如果我在调用 ModelState.IsValid 之前设置了 UserProfile 和\或 UserProfileId,这将无济于事。
处理此问题的正确和安全方法是什么?我当然不应该相信从客户端发送的 UserProfileId 吗?
万一这很重要,我使用的是 asp.net MVC 4。
提前致谢