6

ユーザー モデルの簡単な編集フォームがありますが、ポストバックすると、非表示の入力値がモデルに適用されず、なぜこれが起こっているのかわかりません。

私のカミソリ:

@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てみると(intであるため)ゼロが返されますが、試しRequest["UserId"]てみると正しい値が返されるため、値が正しく投稿されます-UserProfileモデルに追加されません。なぜこれが起こっているのか、それを解決するために私にできることを誰かが知っていますか

ありがとう

4

2 に答える 2

7

パブリック プロパティDefaultModelBinderをバインドできるのはだけです。

プロパティ セッターを public に変更すると、正常に動作するはずです。

[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }

それができない場合は、プライベート セッターを扱うカスタム モデル バインダーを作成する必要があります。

UserProfileただし、直接使用するのではなく、より良いアプローチとして。UserProfileViewModelあなたが公開されている場所を作成UserIdし、ビューとコントローラーのアクションでそれを使用します。この場合、あなたUserProfileとの間でマッピングする必要がありますが、 AutoMapperUserProfileViewModelのようなそのタスクのための優れたツールが存在します。

于 2013-01-22T13:15:12.120 に答える
1

@nemesev が言ったように、Model プロパティのアクセサ プロパティはpublicである必要があります。

モデルバインディングを機能させるためにデータベースクラスをハックする必要がないようにするには、そのクラスのモデルを実際に作成する必要があります。そうすれば、ビューで DTO を使用する必要がなくなります (これは理想的ではありません)。 .

于 2013-01-22T13:17:02.753 に答える