MVC帖子没有向模型添加值

Pet*_*ete 6 .net c# asp.net-mvc razor asp.net-mvc-4

我有一个简单的用户模型编辑表单但是当我回发时,没有任何隐藏的输入值被应用于模型,我不知道为什么会发生这种情况.

我的剃刀:

@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>
}
Run Code Online (Sandbox Code Playgroud)

我的控制器:

    [HttpPost]
    public ActionResult Edit(UserProfile user)
    {
        if (ModelState.IsValid)
        {
            user.Save();
            return RedirectToAction("Index");
        }
        return View(user);
    }
Run Code Online (Sandbox Code Playgroud)

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; }
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试user.UserId它返回零(因为它是一个int),但如果我尝试Request["UserId"]它返回正确的值,以便正确发布值 - 只是没有添加到UserProfile模型中.有谁知道为什么会这样或者我能做些什么来解决它

谢谢

nem*_*esv 7

DefaultModelBinder只能够绑定的公共属性.

将您的属性设置器更改为公共,它应该工作正常:

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
Run Code Online (Sandbox Code Playgroud)

如果你不能这样做,你将需要创建一个自定义模型绑定器来处理私人设置器.

然而,作为一种更好的方法,而不是UserProfile直接使用你 创建UserProfileViewModel您的UserId是公开和使用,在您的视图和控制器的动作.在这种情况下,您需要在您UserProfile和您之间进行映射,UserProfileViewModel但是像AutoMapper这样的任务存在很好的工具.