asp.net-mvc-2 – asp.net-mvc2 – 不使用Model的强类型助手?

在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”的值为“prrrrrrd 2.强类型帮助器从哪里得到它的值?):

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

解决方法

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?

是的,它们首先从ModelState中获取,然后从模型中获取.如果您打算在POST操作中对模型执行某些修改,则需要先从ModelState中删除它们.例如:

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....