asp.net-mvc2 - Strongly typed helpers not using Mo

2019-01-29 03:13发布

When using strongly typed helpers in MVC2 the input field values aren't taken from the Model property when a post is made. Is this default behavior?

(strongly typed) view with strongly typed helpers:

<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>

Controller action for: /Product/Edit/5

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

Html output:

<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>

Controller action for: /Product/Edit/5

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

    }

Html output after form post (below I would expect the value of the input with id="Name" to be "prrrrrrd 2. Where does the strongly typed helper get it's value from?):

<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>

1条回答
Lonely孤独者°
2楼-- · 2019-01-29 03:29

When using strongly typed helpers in MVC2 the input field values aren't taken from the Model property when a post is made. Is this default behavior?

Yes, they are first taken from the ModelState and then from the Model. If you intend to perform some modifications on the model in your POST action you need to remove them from the ModelState first. For example:

[HttpPost]
public ActionResult Edit(Product p)
{
    ModelState.Remove("Name");
    p.Name = "prrrrrrd 2";
    return View(p);
}
查看更多
登录 后发表回答