1

I have a need to create an invoicing function in my mvc application. I have this model class:

public class Product
{
    public int ProductId { get; set; }
    public int SupplierId { get; set; }
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal Price { get; set; }
    public double costPrice { get; set; }
    public string ProductPicUrl { get; set; }
    public ProductCategory Category { get; set; }
    public Supplier Supplier { get; set; }
}

1.I need to make my view display a drop down list of all products (specifically all product names) without using ViewData 2. I need to be able to click a button that goes to my AddToInvoice controller method. I am just not sure how to make it pull the productid out of the dropdownlist and send it to the method.

Can anyone assist? Even if it is just to explain how to make the dropdownlist?

1 Answer 1

4

I usually create a view model that contains both the model I want to create or update and the list of items required to source the data for a specific field. In this case, I would create a view model called SelectProductModel which contains a ProductId property and a Products property.

public class SelectProductModel
{

  public Int32 ProductId { get; set; }
  public IEnumerable<Product> Products { get; set; }

}

In the Invoice controller, I would simply load the list of products and store it in the model:

public ActionResult SelectProduct()
{
  SelectProductModel model = new SelectProductModel();
  model.ProductId = -1;
  model.Products = productRepository.GetList();
  return View();
}

public ActionResult AddToInvoice(Int32? id)
{
  //id is the ProductId sent
}

The SelectProduct view would be a typed view based on this model:

@model SelectProductModel
...
@using(Html.BeginForm(actionName="AddToInvoice", controllerName="Invoice", method=FormMethod.Post))
{

  @Html.DropDownListFor(m => m.ProductId, new SelectList(model.Products, "ProductId", "Name"))
}
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain where productRepository comes from?
productRepository is coming from the data access layer. For the web application shouldn't matter, it should be defined as IRepository<Product>, where IRepository is a simple generic interface that defines basic CRUD operations. The data access layer would implement this interface and it's up to you what you use for your DAL: Entity Framework, NHibernate, ADO.NET classes, etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.