asp.net-mvc2 - Strongly typed helpers not using Model?

风流意气都作罢 提交于 2019-11-28 10:50:22

问题


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:


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);
}


来源:https://stackoverflow.com/questions/7164235/asp-net-mvc2-strongly-typed-helpers-not-using-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!