Aytac
Aytac

Reputation: 335

ViewModel in post action is null

Can someone help me to know why model.Prodis null like in the picture below and model.catg is not null? There are items in my Product table. And also after i add @Html.HiddenFor(p=>p.Prod[i].id) to the view, model.Prod is not null but only id has value. Other parameters are still null.

enter image description here

@model HandMShop.ViewModel.HMViewM

@using (Html.BeginForm("ShopPage", "Shop", FormMethod.Post)) {

@for(int i=0;i< Model.catg.Count;i++)  {
@Html.CheckBoxFor(model => model.catg[i].IsChecked)
<label>@Model.catg[i].CategoryName</label>
 @Html.HiddenFor(model => model.catg[i].id)
 @Html.HiddenFor(model => model.catg[i].CategoryName }

 @for (int i = 0; i < Model.Prod.Count; i++) {
 <div class="col-md-6 col-lg-4">
 <figure class="card card-product mehsul">
 <div class="img-wrap"> <img class="img-fluid mehsulimg" 
 src="@Model.Prod[i].PhotoProducts.First().ImageName" alt=""> </div>
 <div class="handhover">
 <img class="img-fluid" src="@Model.Prod[i].PhotoProducts.Last().ImageName" alt=""> 
 </div>
 <figcaption class="info-wrap">
 <h4 class="title">@Model.Prod[i].ProdName</h4>
 <p class="desc">@Model.Prod[i].Description</p>
 </figcaption>
 </figure>
  </div> 
      }

View Model I used:

public class HMViewM
{
    public List<User> userr { get; set; }
    public List<homesec1slider> homesec1 { get; set; }
    public List<Category>  catg { get;set; }
    public List<Colour> colrs { get; set; }
    public List<PhotoProduct> Photopr { get; set; }
    public List<Product> Prod { get; set; }
    public bool Istehsal { get; set; }
}

Controller

  [HttpPost]
    public ActionResult ShopPage(HMViewM model)
    {
        List<Category> selectedcatg = model.catg.Where(x => x.IsChecked == true).ToList();
        List<Product> selectedprod = model.Prod.Where(i => i.CategoryId == selectedcatg.FirstOrDefault().id).ToList();
        var vm = new HMViewM
        {
            Prod = selectedprod,
            catg = _context.Categories.ToList(),
            colrs = _context.Colours.ToList(),
            Photopr = _context.PhotoProducts.Where(ph => ph.Product.id == ph.ImageId).ToList(),
        };
        return View(vm);
    }

Upvotes: 1

Views: 797

Answers (1)

Arman Ebrahimpour
Arman Ebrahimpour

Reputation: 4461

That's because after page being postbacked by clicking submit button, only those properties will be return to your controller that you explicitly bind them to html input elements. Values that binded in your code is:

@Html.CheckBoxFor(model => model.catg[i].IsChecked)

@Html.HiddenFor(model => model.catg[i].id)
@Html.HiddenFor(model => model.catg[i].CategoryName }

So only these values filled in your controller HMViewM object. If you want other values you should bind them to html input elements too (using hidden field, text, checkbox ...)

Upvotes: 2

Related Questions