Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net asp.net-core-2.0 asp.net-mvc c# html

How to pass form data to ViewModel Properties?

发布于 2020-04-23 13:17:05

I have a .net core 2 code with a simple UI.
I Want to pass data from my form to action method in my controller which accepts a ViewModel parameter ( I Have To Use View Model ) But when I submit my form, I get null as a result. When I Use User as a Parameter type, everything is ok. this is my Code.

My Model

 public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }

My View Model

public class UsersViewModel
    {
        public User NewUser { get; set; }
    }

My Action

[HttpPost]
public IActionResult Index(UsersViewModel user)
  {
      UserDbContext context = new UserDbContext();
      context.Users.Add(user);
      context.SaveChanges();
      return View();
  }

And My View

@model EFCore2.ViewModels.UsersViewModel


<form asp-controller="Home" asp-action="index" method="post">
    <input name="Name" />
    <input name="LastName" />
    <input name="Age" />
    <br />
    <input type="submit" value="Ok" />
</form>

Help Me Please :(

Questioner
Ali Abbasifard
Viewed
17
Hamed Moghadasi 2020-02-10 04:02

As this doc:

The Input tag helper generates appropriate name and id attribute values based on the PageModel property that is assigned to it

In your code, you should add asp-for for all of your inputs. and In the passed viewModel, you just have one property with the datatype of User and don't have direct access to the User properties, so you should access them by calling NewUser.Name and... so your view is going to be like below:

@model EFCore2.ViewModels.UsersViewModel


<form asp-controller="Home" asp-action="index" method="post">
    <input asp-for="NewUser.Name" name="Name" />
    <input asp-for="NewUser.LastName"  name="LastName" />
    <input asp-for="NewUser.Age"  name="Age" />
    <br />
    <input type="submit" value="Ok" />
</form>

good luck.