У меня есть представление с двумя раскрывающимися списками, первый с категорией продукта, а второй зависит от выбранного списка категорий продуктов. Когда нажимаете кнопку сохранения и ajax перенаправляете на Post AddOrEditPartial в контроллере, мой объект модели имеет только автоматически сгенерированные Id и CreateAt. Все остальные данные из выпадающих списков и поля количества равны нулю. Я не могу найти, в чем проблема. Может кто-нибудь помочь?
public class Warehouse : BaseEntity
{
[Required(ErrorMessage = "Category Required")]
public string IdCategory { get; set; }
[Required(ErrorMessage = "Product Required")]
public string IdProduct { get; set; }
[Required(ErrorMessage = "Quantity required")]
public int Quantity { get; set; }
}
public class WarehouseViewModel
{
public Warehouse Warehouse { get; set; }
public IEnumerable<ProductCategory> ProductCategories1 { get; set; }
public IEnumerable<Product> Products { get; set; }
}
IndexView
@using (Ajax.BeginForm("AddOrEditPartial", "Warehouse", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "formsubmit", OnSuccess = "closePopUp(data)" }))
{
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Product</h4>
</div>
<div class="modal-body" id="modbody">
@Html.Partial("AddOrEditPartial")
</div>
</div>
</div>
</div>
}
PartialView
@model MyShop.Core.ViewModels.WarehouseViewModel
<div class="panel-group">
<div class="panel-default">
<div class="panel panel-success">
<div class="panel-heading">Succes Implement Add/Edit Button</div>
<div class="panel-body" id="panbody">
<div class="col-sm-12">
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Warehouse.Id)
<div class="form-group">
@Html.LabelFor(model => model.Warehouse.IdCategory, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Warehouse.IdCategory, new SelectList(Model.ProductCategories1, "Category", "Category"), "Please select Category", new { @class = "form-control" })
@*@Html.DropDownListFor(model => model.Warehouse.Category, (IEnumerable<SelectListItem>)new SelectList(ViewBag.Cat, "Category", "Category"), "Please select Category", new { @class = "form-control" })*@
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Warehouse.IdProduct, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.Warehouse.IdProduct, (IEnumerable<SelectListItem>)new SelectList(ViewBag.Prod, "Name", "Name"), "Please Select Product", new { @class = "form-control" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Warehouse.Quantity, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Warehouse.Quantity, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Warehouse.Quantity, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-success" id="btnSubmit" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Warehouse_IdCategory").change(function () {
var prodId = $(this).val();
console.log(prodId);
//debugger
$.ajax({
type: "GET",
url: '@Url.Action("GetProductList", "Warehouse")/' +prodId,
data: { prodId: prodId },
contentType: "html",
success: function (response) {
//debugger
$("#Warehouse_IdProduct").empty();
$("#Warehouse_IdProduct").append(response);
}
})
})
})
</script>
Controller
public ActionResult Index()
{
WarehouseViewModel whViewModel = new WarehouseViewModel();
whViewModel.Warehouse = new Warehouse();
whViewModel.ProductCategories1 = productCategories.Collection();
whViewModel.Products = contextProduct.Collection();
return View(whViewModel);
}
[HttpPost]
public ActionResult AddOrEditPartial(Warehouse wh)
{
if (!ModelState.IsValid)
{
return Json(new { success = false });
}
else
{
var data = context.Find(wh.Id);
if (data != null)
{
data.IdProduct = wh.IdProduct;
data.IdCategory = wh.IdCategory;
data.Quantity = wh.Quantity;
context.Commit();
}
else
{
context.Insert(wh);
context.Commit();
}
return Json(new { success = true });
}
}