Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Unfortunately, some of what you are doing cannot be avoided. There needs to be some form of model and view selection based on category.</p> <p>Use a factory pattern. Create a base class:</p> <pre><code>public abstract class BaseCategory { public abstract string GetViewName(); public abstract Object CreateModelFromFormData(); } </code></pre> <p>For each category, create a sub-class derived from <code>BaseCategory</code> and implement the abstract functions.</p> <p>In your action, do the following:</p> <pre><code>public ActionResult PostAd(string categoryName, string subCategoryName) { BaseFactory factory; if (categoryName == "Vehicle") { if (subCategoryName == "Cars") { factory = new CarsFactory(); } else ... } else ... return View(factory.GetViewName(), factory.CreateModelFromFormData()); } </code></pre> <p>I have a couple reasons for this schema:</p> <ol> <li><p>I am purposefully using <code>if/else</code> for the factory selection. Your controller is going to be created and re-created for every action call. So pre-populating a list will constantly and needlessly create objects for categories that will not be selected. A simple <code>if/else</code> will be more efficient. If you want to prevent the <code>if/else</code>, you can put your factories in a <code>Dictionary</code> and select based on the categories, but that would be a lot of needless constructor actions.</p></li> <li><p>I made the <code>CreateModelFromFormData</code> a function because I assume you'll need to copy data from the posted form data. This may require passing in data, but I left the function parameterless. </p></li> <li><p>I used base/derived classes because the copying of the form data will probably need to be custom from the model being created and the form data being posted. Also, saving to persistent storage (file or database) may be category-specific as well.</p></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload