【发布时间】:2013-01-22 13:04:58
【问题描述】:
我有一个用户模型的简单编辑表单,但是当我回发时,没有任何隐藏的输入值被应用于模型,我不确定为什么会发生这种情况。
我的剃刀:
@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);
}
UserProfile 类:
[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,它会返回零(因为它是一个整数),但如果我尝试Request["UserId"],它会返回正确的值,因此该值被正确发布——只是没有添加到UserProfile 模型中。有谁知道为什么会发生这种情况或我能做些什么来解决它
谢谢
【问题讨论】:
-
隐藏字段生成的html是什么样子的?您也可以发布您的 UserProfile 模型吗?
-
-
生成的 HTML 看起来不错。那么你能用
UserProfile类的定义更新你的帖子吗? -
你的路由中是否有一个名为 UserId 的参数?
-
不,我还没有触及路由文件,添加了 userprofile 类
标签: c# .net asp.net-mvc razor asp.net-mvc-4