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 :(
As this doc:
The Input tag helper generates appropriate
name
andid
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.
Nope. It Doesn't work :(
does it come to your action method ?!
yes. when i debug, it comes to action. as i mentioned, when i use User type instead of UsersViewModel, it works well.
ahan baba, I update Answer
Your ViewModel just has
User
.. and don't know anything about 'Name','LastName' and ...