我有一个用户模型的简单编辑表单,但是当我回发时,没有任何隐藏的输入值被应用于模型,我不确定为什么会发生这种情况。
我的剃须刀:
@model CMS.Core.Models.UserProfile
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset class="normalForm">
<legend>User Profile</legend>
@Html.HiddenFor(model => model.UserId)
<div class="formRow">
<div class="editor-label">
@Html.LabelFor(model => model.EmailAddress)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.EmailAddress, new { @class = "textbox" })
@Html.ValidationMessageFor(model => model.EmailAddress)
</div>
</div>
<div class="formRow">
<div class="editor-label">
@Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
@Html.TextBoxFor(model => model.FirstName, new { @class = "textbox" })
@Html.ValidationMessageFor(model => model.FirstName)
</div>
</div>
<div class="buttonRow"><input type="submit" value="Save" class="button" /></div>
</fieldset>
}
我的控制器:
[HttpPost]
public ActionResult Edit(UserProfile user)
{
if (ModelState.IsValid)
{
user.Save();
return RedirectToAction("Index");
}
return View(user);
}
用户配置文件类:
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; private set; }
[Required(ErrorMessage = "Please enter an email address")]
[StringLength(350)]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
[StringLength(100)]
[DataType(DataType.Text)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
}
如果我尝试user.UserId
它返回零(因为它是一个 int),但如果我尝试Request["UserId"]
它返回正确的值,因此该值被正确发布 - 只是没有添加到UserProfile
模型中。有谁知道为什么会这样或者我能做些什么来解决它
谢谢