0

My problem I get a null value of Supplier(which is a foreign key in Purchase table) when I submit edit or create purchase action successfully!

My Question: How to get the foreign key value submitted to the table instead of getting null value?

Here is my models:

 public class Purchase
{

    [Required(ErrorMessage = "Invoice No. must be uniqe!")]
    [Display(Name = "Invoice No.")]
    public string Id { get; set; }
    [Display(Name = "yyyy-MM-dd")]
    [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime date { get; set; }
    //[Display(Name = "Supplier")]
    //public int supplier_id { get; set; }
    [Display(Name = "Qty")]
    public decimal amount { get; set; }
    [Display(Name = "Discount")]
    public decimal? discount { get; set; }
    [Display(Name = "Total")]
    [Required]
    public decimal grand_total { get; set; }
    [Display(Name = "Paid?")]
    public bool is_paid { get; set; }
    [Display(Name = "Last update")]
    public DateTime? last_updated { get; set; }
    [Display(Name = "Description")]
    public string description { get; set; }


    public virtual Supplier Supplier { get; set; }
    public virtual ICollection<PurchaseProduct> PurchaseProducts { get; set; }
}



public class Supplier
{
    public Supplier()
    {
        this.address = "N/A";
    }
    public int ID { get; set; }

    [Required]
    [StringLength(50, ErrorMessage = "Only 50 characters allowed!")]
    public string name { get; set; }

    public string address { get; set; }
    public string contact { get; set; }
    public string description { get; set; }

    public virtual ICollection<Purchase> Purchases { get; set; }
}

All suppliers retrieved from Supplier table to purchases view in Viewbag dictionary as dropdownlist

Here is my create action:

  public ActionResult Create()
{
    //var model = db.Suppliers.FirstOrDefault();
    ViewBag.MyHeaders2 = new SelectList(db.Suppliers, "ID", "name");
    return View();
}

// POST: Purchases/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,date,supplier_id,amount,discount,grand_total,is_paid,last_updated,description")] Purchase purchase)
{
    if (ModelState.IsValid)
    {
        db.Purchases.Add(purchase);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(purchase);
}

and here is the dropdownlist in my Create view:

@model PointOfSales.Models.Purchase
        <div class="form-group">
            @Html.LabelFor(model => model.Supplier, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.Supplier, (SelectList)ViewBag.MyHeaders2, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.Supplier, "", new { @class = "text-danger" })
            </div>
        </div>

enter image description here

Ayman
  • 580
  • 9
  • 27
  • 1
    You cannot bind a `` binds to a posts back a simple value). You model needs a navigation property (typically type of `int` which is the FK to your `Supplier` table), and you bind to that. –  Sep 10 '18 at 22:38
  • @StephenMuecke Sorry, but it did select all suppliers from supplier table and I get them in my dropdownlist – Ayman Sep 10 '18 at 22:46
  • 1
    Yes I know, but the problem is that you are trying to bind to your `Supplier Supplier` which is a complex object - and that cannot be done as I stated in my first comment. You need to bind to an `int` property. And I suggest you also read [Relationships, navigation properties and foreign keys](https://learn.microsoft.com/en-us/ef/ef6/fundamentals/relationships) –  Sep 10 '18 at 22:48
  • @StephenMuecke Thank you Mr. Muecke – Ayman Sep 10 '18 at 22:50
  • 1
    The I suggest you read [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) and stop using data models in your view do this property by using a view model which will contain an `int SelectedSupplier` and `IEnumerable SupplierOptions` property –  Sep 10 '18 at 22:51
  • 1
    You will also want to read [The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable'](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) because the code in your POST method will throw that exception –  Sep 10 '18 at 22:56

0 Answers0