i am new to web from desktop.
i have two models.
first
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public double Price { get; set; }
public double Stock { get; set; }
public Category Category { get; set; }
public string ImagePath { get; set; }
}
and second is
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public bool isSelected { get; set; }
}
and a ViewModel for passing it to my view
public class ProductsVM
{
public IList<Item> items { get; set; }
public IList<Category> categories { get; set; }
}
and my controller action method looks like this
[HttpGet]
public ActionResult Products()
{
ViewBag.Message = "...Products...";
ProductsVM productsVm = new ProductsVM();
productsVm.items = db.Items.ToList();
productsVm.categories = db.Categories.ToList();
return View(productsVm);
}
[HttpPost]
public ActionResult Products(ProductsVM model)
{
ViewBag.Message = "...Categories...";
return View(model);
}
i have used it in my view like this
@using (Html.BeginForm())
{
<div class="row">
<div class="col-md-2">
@foreach (var it in Model.categories.ToList())
{
<div class="input-group">
@Html.CheckBoxFor(i => it.isSelected, new { Name = "ChkCategory", id = "ChkCategory"+it.Id, @class = "Categories" }) @it.Name
@Html.HiddenFor(i => it.Name)
</div>
}
</div>
@*Loading Items...*@
<div class="col-md-10">
@for (int i = 0; i < Model.items.Count() / 3; i++)
{
<div class="row">
@foreach (var item in Model.items.Skip(i * 3).Take(3))
{
<div class="col-md-4 col-sm-6 col-xs-12">
<img src="@Url.Content(item.ImagePath)" alt="@item.Description" class="thumbnail" />
</div>
}
</div>
}
</div>
</div>
<input type="submit" value="submit" />
}
@section scripts
{
<script src="~/Scripts/Products.js"></script>
}
i have tried all the ways to get my model back when i post the from to controller
i am posting the from on checkbox click event using ajax from my products.js file.
but in my controller action method it always show the ViewModel as null.
what should i do? am i doing something wrong.
Products.js
$(function () {
console.log('Inside js......');
$('.Categories').click(function (e) {
console.log(this.id, $("#" + this.id).is(":checked"));
$.ajax({
type: "POST",
url: "/Home/Products",
success: function () {
console.log("ajax successfull....");
},
error: function () {
console.log("ajax error....");
}
});
});
});