1

MVC2で強く型付けされたヘルパーを使用する場合、投稿が行われるときに入力フィールドの値はModelプロパティから取得されません。これはデフォルトの動作ですか?

(強く型付けされた)ヘルパーを強く型付けしたビュー:

<div class="editor-label">
    <%: Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.Name) %>
    <%: Html.ValidationMessageFor(model => model.Name) %>
</div>

<div class="editor-label">
    <%: Html.LabelFor(model => model.Price) %>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.Price) %>
    <%: Html.ValidationMessageFor(model => model.Price) %>
</div>

コントローラーアクション:/ Product / Edit / 5

    public ActionResult Edit(int id)
    {
        var p = new Product();
        p.Name = "product 1";
        p.Price = "100";
        return View(p);
    }

HTML出力:

<div class="editor-label">
    <label for="Name">Name</label>
</div>

<div class="editor-field">
    <input id="Name" name="Name" type="text" value="product 1" />
</div>

<div class="editor-label">
    <label for="Price">Price</label>
</div>
<div class="editor-field">
    <input id="Price" name="Price" type="text" value="100" />
</div>

コントローラーアクション:/ Product / Edit / 5

    [HttpPost]
    public ActionResult Edit(Product p)
    {
        p.Name = "prrrrrrd 2";
        return View(p);

    }

フォーム投稿後のHTML出力(以下では、id="Name"の入力値は"prrrrrrd2であると予想されます。強く型付けされたヘルパーはどこから値を取得しますか?):

<div class="editor-label">
    <label for="Name">Name</label>
</div>

<div class="editor-field">
    <input id="Name" name="Name" type="text" value="product 1" />
</div>

<div class="editor-label">
    <label for="Price">Price</label>
</div>
<div class="editor-field">
    <input id="Price" name="Price" type="text" value="100" />
</div>
4

1 に答える 1

4

MVC2で強く型付けされたヘルパーを使用する場合、投稿が行われるときに入力フィールドの値はModelプロパティから取得されません。これはデフォルトの動作ですか?

はい、最初にModelStateから取得され、次にModelから取得されます。POSTアクションでモデルにいくつかの変更を実行する場合は、最初にそれらをModelStateから削除する必要があります。例えば:

[HttpPost]
public ActionResult Edit(Product p)
{
    ModelState.Remove("Name");
    p.Name = "prrrrrrd 2";
    return View(p);
}
于 2011-08-23T16:22:17.247 に答える