You seem to be getting very confused.
SupplierandCategoryViewModel
CategoryModel
is the list of categories;SupplierModel.Category
is the selected category;
View:
@Html.DropDownListFor(x => x.CategoryModel, ...
You are trying to render a drop-down list to select
the entire list of categories. You should be selecting the single category instead.
Controller:
public ActionResult Save(SupplierandCategoryViewModel Supply)
{
...
Category = Supply.CategoryModel
You are trying to store
the list of categories in a property which can only store
a single category.
Start by simplifying your view model:
public class SupplierandCategoryViewModel
{
public int Id { get; set; }
public string SupplierCode { get; set; }
public string SupplierName { get; set; }
public int SupplierContact { get; set; }
public int CategoryId { get; set; }
public IEnumerable<Category> AllCategories { get; set; }
}
Then update your actions:
public ActionResult New()
{
var viewModel = new SupplierandCategoryViewModel
{
AllCategories = _SBC.Categorys.ToList(),
};
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(SupplierandCategoryViewModel viewModel)
{
Supplier supplier;
if (viewModel.Id == 0)
{
supplier = new Supplier();
_SBC.Suppliers.Add(supplier);
}
else
{
supplier = _SBC.Suppliers.Single(s => s.Id == viewModel.Id);
}
supplier.SupplierName = viewModel.SupplierName;
supplier.SupplierCode = viewModel.SupplierCode;
supplier.SupplierContact = viewModel.SupplierContact;
supplier.Category = _SBC.Categorys.Single(c => c.Id == viewModel.CategoryId);
_SBC.SaveChanges();
return View();
}
Then your form becomes:
...
@using (Html.BeginForm("Save", "Supplier"))
{
@Html.AntiForgeryToken()
<div class="form-group">
@Html.LabelFor(x => x.CategoryId)
@Html.DropDownListFor(x => x.CategoryId, new SelectList(Model.AllCategories, "Id", "CatName"), "Select Supplier Category", new { id="myCat", @class="form-control" })
</div>
<div class="form-group">
@Html.LabelFor(x => x.SupplierCode)
@Html.TextBoxFor(x => x.SupplierCode, new { @class="form-control" })
</div>
<div class="form-group">
@Html.LabelFor(x => x.SupplierName)
@Html.TextBoxFor(x => x.SupplierName, new { @class="form-control" })
</div>
<div class="form-group">
@Html.LabelFor(x => x.SupplierContact)
@Html.TextBoxFor(x => x.SupplierContact, new { @class="form-control" })
</div>
<p><button type="submit" class="btn btn-primary">Save</button></p>
}
You'll probably want to add some validation attributes to your view model:
Validation with the Data Annotation Validators (C#) | Microsoft Docs[
^]