代码之家  ›  专栏  ›  技术社区  ›  narue1992

ASP。NET Core 8 MVC:如果子类属性存在,则模型值不会在POST中传递回

  •  0
  • narue1992  · 技术社区  · 6 月前

    出于某种原因,当我使用儿童财产作为 asp-for 值,HTTP Post 模型属性显示它们没有被修改,我的 ModelState 验证不会触发。

    以下是示例视图

    @model ViewModel
    <form asp-action="Login" asp-controller="App" method="POST">
       <input asp-for="subClass1.user.email_addr" type="text" class="form-control" autocomplete="on" />
       
       <input asp-for="test" type="text" class="form-control" autocomplete="on" />
    </form>
    

    模型

    public class ViewModel
    {
        public string test { get; set; } = "test value";
        public User subClass1 = new User();
    }
    
    public class User 
    {    
         public UserL user { get; set; } = new UserL();
    }
    
    public class UserL
    {
        [CustomEAttribute]
        public string? email_addr { get; set; } 
    }
    

    超文本传输协议 POST 方法:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Login(ViewModel model, Microsoft.AspNetCore.Http.IFormCollection collection)
    {
       // I've also found ModelState is not triggered on subClass1 
       // properties... only the 'test' property triggered.
       if (!ModelState.IsValid)
       {
       }
    }
    

    从我的控制器中可以看出,该物业 ViewModel model 未更改(即未返回我的视图输入值) email_addr .

    我试过用 @Html.TextBoxFor 而不是简单的html输入,我仍然没有运气。

    网上有很多例子表明,你应该能够毫无问题地完成我上面的例子,所以不确定我的代码有什么问题。

    我确实知道 Microsoft.AspNetCore.Http.IFormCollection 收藏属性确实显示 subClass1.user.email_addr 正在设置。那么,为什么在“模型”中访问相同的值不起作用呢?

    1 回复  |  直到 6 月前
        1
  •  1
  •   Victor    6 月前

    在ASP.NET中定义数据模型时。NET MVC需要使用属性而不是字段。如果使用字段,MVC引擎将无法正确进行数据绑定。将视图模型声明更改为:

    public class ViewModel
    {
        public string test { get; set; } = "test value";
        public User subClass1 { get; set; } = new User();
    }