New.cshtml:
<div class="form-group ">
<b>Brand</b>
@Html.DropDownListFor(m => m.item.brand, new SelectList(Model.Brandlist, "Name" , "Name"), "Search Brand", htmlAttributes: new { @class = "form-control input-xs", id = "search", style = "width:240px;" })
</div>
Index.cshtml:
foreach (var lst_Item in Model)
{
<tr>
<td>@lst_Item.brand</td>
<td>@lst_Item.category</td>
</tr>
}
Item's view model:
public class newItemsVM
{
public IEnumerable<Category> Categorylist { get; set; }
public IEnumerable<Brand> Brandlist { get; set; }
public Item item { get; set; }
}
Controller
public ActionResult Save(newItemsVM newItemsVM)
{
if (newItemsVM.item.id == 0)
{
_context.tbl_item.Add(newItemsVM.item);
}
else
{
var Itemdb = _context.tbl_item.Single(c => c.id == newItemsVM.item.id);
Itemdb.name = newItemsVM.item.name;
Itemdb.description = newItemsVM.item.description;
Itemdb.brand = newItemsVM.item.brand;
Itemdb.category = newItemsVM.item.category;
Itemdb.shelfno = newItemsVM.item.shelfno;
Itemdb.stock = newItemsVM.item.stock;
Itemdb.price = newItemsVM.item.price;
}
try
{
_context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("New", "Item"); ;
}
I want the dropdown list to show all the stored brands' name when selecting a particular brand from the dropdownlist and to show the brand's name in the view page when submit button is clicked.
But I want to store the selected brand's id into database not the name actually.
While in database it's storing the brand's name not the id.
You made mistake in map property of DropDown:
Your
Brandlook like follows as per my assumption:Brand.cs
While supplying your Brandlist to Razor you have to supply both
IdandNameFollowing your model looks like while supplying to the Razor:
Now in razor page in Dropdown you have to map both Id and Name like follows:
after above changes you will get brand id at the time of Save.
Hope this will work for you!!
Note: Make sure ItemDB entity property
brandis an int