Janusz Szum
Janusz Szum

Reputation: 17

BeginForm dont sent model to Controller method POST why?

I have problem i dont now how to fix it.

I have ViewModel

public class CartOrderViewModel
{
    public Cart Carts;
    public Order Orders;
    public string name;
}

in CartController method

public async Task<IActionResult> Index()
{
 CartOrderViewModel vm = new CartOrderViewModel
            {
                Carts = _cart,
                Orders = new Order() { User = applicationUser },
            };
return View(vm);
}

View Index from CartController

@using (Html.BeginForm("Test", "Cart", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.name)

    <input type="submit" value="Submit" />
}

and in my method Test in CartController i dont see ViewModel CartOrderViewModel

[HttpPost]
public IActionResult Test(CartOrderViewModel test)
{
      string komentarz = test.name;
      return View();
}

Model: test in null. Please help me. Thx a lot

How to send form from Index View from CartController my ViewModel CartOrderViewModel example Model.Order.name ??

Why my name from CartOrderViewModel dont sent to method Test from index View ?

printscreen

enter image description here

Upvotes: 1

Views: 89

Answers (1)

Dai
Dai

Reputation: 155438

Why my name from CartOrderViewModel dont sent to method Test from index View ?

ASP.NET binds to properties, not fields. Change all of the public fields in class CartOrderViewModel to be mutable properties with { get; set; }.

Like so:

public class CartOrderViewModel
{
    public Cart?   Carts  { get; set; }
    public Order?  Orders { get; set; }
    public String? Name   { get; set; }
}

Don't forget to add validation attributes, such as [Required], as per your project's needs.

Upvotes: 1

Related Questions