我有一個簡單的用戶模型編輯窗體,但是當我回發,沒有任何隱藏的輸入值被應用於模型,我不知道爲什麼會發生這種情況。MVC後不向模型添加值
我的剃刀:
@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
模型。有誰知道爲什麼發生這種情況還是我能做些什麼來解決它
感謝
如何爲隱藏字段生成html外觀?你也可以發佈你的UserProfile模型嗎? – nemesv
– Pete
生成的HTML看起來很好。那麼你可以用你的'UserProfile'類的定義來更新你的文章嗎? – nemesv