Blake Rivell Blake Rivell -4 years ago 117
C# Question

Defining a ViewModel for a razor partial that will either display a form if only one and a table if multiple

I need to create a Partial View with MVC that will either show a List of items if more than one or an html form if only one.

Should I create a ViewModel specifically for this partial that has the following:

public Product Product { get; set; }
public IEnumerable<Product> Product { get; set; }

Or would I be better off just sending the list. If I just send the list will I be able to bind the first (and only) item to the form?

The goal is to bind the single product properties to the form if only one and if multiple loop through them and output in an html table.

Answer Source

It seems simpler to me if the model contains a single property -- call it Products since it's a collection. In the view, test its Count() and either render the form or the table. Binding won't be a problem -- just take the First() item if the Count() == 1.

If you have two properties, what will you do if they both have data? What if the product in the single-value property is different from the first one in the collection? Which one wins?

You can solve these problems by enforcing business rules in the controller or on the model itself -- but yuo can avoid them entirely if you just have a collection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download