asp.net-mvc - ASP.NET Core TagHelper 输入 asp-for 渲染值属性与请求模型中的原始值保持一致

标签 asp.net-mvc asp.net-core model-binding tag-helpers asp.net-core-tag-helpers

我使用 asp.net core 3.1 构建了一个简单的网页来重现问题。同一个 HomeController.cs 中有 2 个操作。

一个用于渲染 html 表单,另一个用于接收表单发布数据然后再次渲染表单。

public class HomeController : Controller
{
        // rendering form
        [HttpGet]
        public IActionResult Index()
        {
            var myForm = new MyForm();
            myForm.Id = 100;
            return View("index", myForm);
        }

        // after form post, rendering form with updated value.
        [HttpPost]
        public IActionResult Index(MyForm m)
        {
            m.Id = 200;
            return View("index", m);
        }
}

我使用asp.net core tag helperindex.cshtml

@model MyForm

<div>
    <form asp-controller="Home" asp-action="Index" method="post">
        <span>@Model.Id</span>
        <input type="text" asp-for="@Model.Id"/>
        <button type="submit">Submit</button>
    </form>
</div>

当我 GET/index 时,一切都很好,span 中的 @Model.Id 和输入值都是 100

获取/index 的 Http 响应

<form method="post" action="/">
        <span>100</span>
        <input type="text" data-val="true" 
               data-val-required="The Id field is required."
               id="Id" name="Id" value="100">
        <button type="submit">Submit</button>
</form>

但是当我发布表单时,我期望跨度和输入中的值都应为200,但跨度为200,表单为100

输入 100 的 POST/index 的 Http 响应

<form method="post" action="/">
        <span>200</span>
        <input type="text" data-val="true" 
               data-val-required="The Id field is required."
               id="Id" name="Id" value="100">
        <button type="submit">Submit</button>
</form>

我猜“asp-for”选择从原始 ModelState 读取数据,该模型是在模型绑定(bind)时构建的。而不是读取为 View Razor 渲染传递的 ViewModel。

有谁知道为什么标签助手 asp-for 会有这样的行为吗?我应该如何避免这种行为并让 asp-for 使用我在 View("index", m) 中传递的模型

最佳答案

I guess "asp-for" choose to read data from original ModelState

是的,这是设计使然。默认 TagHelper 显示 ModelState 值而不是 Model。

如果您希望 asp-for 显示更新后的模型值,您可以在发布操作中添加 ModelState.Clear();

public IActionResult Index(MyForm m)
{
    ModelState.Clear();
    m.Id = 200;
    return View("index", m);
}

关于asp.net-mvc - ASP.NET Core TagHelper 输入 asp-for 渲染值属性与请求模型中的原始值保持一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64469706/

相关文章:

c# - 在 AWS CDK 中使用常量 JSON 参数创建规则 (C#)

c# - 具有相同名称的路由参数和 View 模型属性 - 意外行为

asp.net-web-api - 自定义模型 Binder :Can't bind parameter 'xxx' because it has conflicting attributes on it

asp.net-mvc - 如何在一个 View 中处理两个表单

c# - ApplicationDbContext 不实现接口(interface)

html - MVC中文本区域的宽度

c# - 使用拥有的类型时,Entity Framework Core 尝试连接到不存在的表

asp.net-mvc - ASP.Net MVC 5 w/identity 2.2.0 注销不起作用

azure - 无法使用 NuGet 安装 Microsoft.Azure.ServiceBus

asp.net-mvc - MVC3 如何将多个复选框绑定(bind)到 ViewModel 中的 1 个属性