Asp.net core model doesn't bind from form

后端 未结 10 906
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 13:54

I catch post request from 3rd-side static page (generated by Adobe Muse) and handle it with MVC action.

10条回答
  •  盖世英雄少女心
    2021-02-02 14:26

    I had the same problem and I want to share what happened in my case and how I got the solution. Perhaps, someone may find it useful to know.

    My context was ASP.NET Core 3.1 Razor pages. I had a handler as

    public async Task OnPostLogin([FromForm] LoginInput loginData)
    {
      
    }
    

    and also I had a property in my ViewModel as

      public LoginInput LoginInput { get; set; }
    

    And in my Razor page, I have used the form like this:

     
    
     
    
     .....
     
            
    

    So, notice that, in my form, I used the property LoginInput.UserNameOrEmail, but in my handler's parameter, I used the parameter name loginData. How will the ASP.NET Core know that, this LoginInput.UserNameOrEmail is actually loginData.UserNameOrEmail. It can't, right? Therefore, it did not bind my form data.

    Then, when I renamed my ViewModel property "LoginInput" to the same name as the handler parameter, like this:

    public LoginInput LoginData { get; set; }
    

    The ASP.NET Core then found that the form data was matching the parameter name and then it started to bind properly. My problem was solved.

提交回复
热议问题