我有一个简单的用户模型编辑表单,但是当我回发时,没有任何隐藏的输入值被应用到模型,我不确定为什么会这样。
我的 Razor :
@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>
}
我的 Controller :
[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
它返回零(因为它是一个整数)但是如果我尝试 Request["UserId"]
它返回正确的值所以值被正确发布 - 只是没有添加到 UserProfile
模型中。有谁知道为什么会这样或者我能做些什么来解决它
谢谢
最佳答案
DefaultModelBinder
只能绑定(bind)公共(public)属性。
将您的属性 setter 更改为公共(public),它应该可以正常工作:
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
如果您不能这样做,您将需要创建一个自定义模型绑定(bind)器来处理私有(private) setter 。
然而,作为一种更好的方法,而不是直接使用您的 UserProfile
。创建一个 UserProfileViewModel
,其中您的 UserId
是公开的,并在您的 View 和 Controller 操作中使用它。在这种情况下,您需要在 UserProfile
和 UserProfileViewModel
之间进行映射,但是有一些很好的工具可以完成该任务,例如 AutoMapper .
关于c# - MVC 发布不向模型添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459247/