0

I'm attempting to create a single Controller class to handle all foreseeable surveys that I'll end up creating in the future. Currently I have a 'Surveys' table with fields: Id, SurveyName, Active. On the 'master' Surveys' Index page I list out every SurveyName found in that table. Each SurveyName is clickable, and when clicked on, the page sends the SurveyName as a string to the receiving controller action. Said controller action looks like this:

    //
    //GET: /Surveys/TakeSurvey/
    public ActionResult TakeSurvey(string surveyName)
    {
        Assembly thisAssembly = Assembly.GetExecutingAssembly();
        Type typeToCreate = thisAssembly.GetTypes().Where(t => t.Name == surveyName).First();

        object newSurvey = Activator.CreateInstance(typeToCreate);

        ViewBag.surveyName = surveyName;

        return View(surveyName, newSurvey);
    }

Using reflection I am able to create a new instance of the type (Model) designated by the passed-in string 'surveyName' and am able to pass that Model off to a view with the same name.

EXAMPLE
Someone clicks on "SummerPicnic," the string "SummerPicnic" is passed to the controller. The controller, using reflection, creates a new instance of the SummerPicnic class and passes it to a view with the same name. A person is then able to fill out a form for their summer picnic plans.

This works all fine and dandy. The part that I'm stuck at is trying to save the form passed back by the POST method into the correct corresponding DB table. Since I don't know ahead of time what sort of Model the controller will be getting back, I not only don't know how to tell it what sort of Model to save, but where to save it to, either, since I can't do something ridiculous like:

    //
    //POST: Surveys/TakeSurvey
    [HttpPost]
    public ActionResult TakeSurvey(Model survey)
    {

        if (ModelState.IsValid)
        {
            _db. + typeof(survey) + .Add(survey);
            _db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }

        return View();
    }

Is there a way to do this, or should I go about this from a whole different angle? My ultimate goal is to have a single Controller orchestrating every simple-survey, so I don't have to create a separate controller for every single survey I end up making down the road.

An alternative solution I can think of is to have a separate method for every survey, and to have which method to call defined inside of every survey's view. For example, if I had a SummerPicnic survey, the submit button would call an ActionMethod called 'SummerPicnic':

@Ajax.ActionLink("Create", "SummerPicnic", "Surveys", new AjaxOptions { HttpMethod = "POST" })

A survey for PartyAttendance would call an ActionMethod 'PartyAttendance,' etc. I'd rather not have to do that, though...

UPDATE 1 When I call:

    _db.Articles.Add(article);
    _db.SaveChanges();

This is what _db is:

    private IntranetDb _db = new IntranetDb();

Which is...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace Intranet.Models
{
    public class IntranetDb : DbContext
    {
        public DbSet<Article> Articles { get; set; }
        public DbSet<ScrollingNews> ScrollingNews { get; set; }
        public DbSet<Survey> Surveys { get; set; }
        public DbSet<Surveys.test> tests { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }
    }
}
JJJ
  • 32,902
  • 20
  • 89
  • 102
Caleb Bergman
  • 858
  • 1
  • 8
  • 18
  • (somewhat unrelated to the question) there's an asp.net mvc survey os app, all actions ajax http://surveymaster.codeplex.com – Omu Jun 15 '12 at 23:36
  • I updated my answer you can give a shot.. my initial answer got some errors though – VJAI Jun 16 '12 at 17:06
  • It may be unrelated to the **particular** problem but it's an excellent alternative that I'll definitely be looking in to. I've been searching for a good (free) Survey Engine and hadn't come across one yet. Thank you :) – Caleb Bergman Jun 18 '12 at 16:14
  • curious, how do you dynamically load the view? modified viewengine that also uses "surveyname" param to find right view? – diegohb Aug 31 '13 at 19:14

3 Answers3

2

You can try something like this,

UPDATE:

The built-in UpdateModel will work with generic model see this post, so we got little more work.

[HttpPost]
public ActionResult TakeSurvey(FormCollection form, surveyName)
{
  var surveyType = Type.GetType(surveyName);
  var surveyObj = Activator.CreateInstance(surveyType);

  var binder = Binders.GetBinder(surveyType);

  var bindingContext = new ModelBindingContext()
  {
    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => surveyObj, surveyType),
    ModelState = ModelState,
    ValueProvider = form
  };

  binder.BindModel(ControllerContext, bindingContext);

  if (ModelState.IsValid)
  {
    // if "db" derives from ObjectContext then..
    db.AddObject(surveyType, surveyObj);         
    db.SaveChanges();

    // if "db" derives from DbContext then..
    var objCtx = ((IObjectContextAdapter)db).ObjectContext;        
    objCtx.AddObject(surveyType, surveyObj);         
    db.SaveChanges();

    return RedirectToAction("Index", "Home");
  }

  return View();
}

Check this two know the diff between DbContext and ObjectContext

Community
  • 1
  • 1
VJAI
  • 32,167
  • 23
  • 102
  • 164
  • When you say "// save surveyObj to db" how exactly would I go about that? The only way I know how is by grabbing the db, the corresponding table and calling save() on it. ex. _db.Articles.Save(); or _db.SummerPicnic.Save(); or _db.PartyAttendance.Save(); How do I dynamically write a statement to do that? Or am I just not following your logic and that's not the way you'd do it :/ – Caleb Bergman Jun 18 '12 at 16:05
  • @cbergman One option is to use reflection and find the the particular type(SummerPicnic, PartyAttendance) in _db and call the Save method. I'll update the code if you need. – VJAI Jun 18 '12 at 16:19
  • Is that object _db is created by EF or L2SQL? – VJAI Jun 18 '12 at 16:20
  • I would appreciate that greatly kind sir. Ummm, I do believe EF. At least when I'm creating the controllers I've been selecting "Controller with read/write actions and views, using **Entity Framework**" ;) – Caleb Bergman Jun 18 '12 at 16:27
  • The entity framework has a generic method called AddObject that takes the type name and object as the parameters so you can use that and avoid reflection (plz see the updated answer) – VJAI Jun 18 '12 at 16:57
  • Hmmm...maybe I am using L2SQL. I'm not getting the AddObject method to come up. Let me update my question with DB information. One moment... – Caleb Bergman Jun 18 '12 at 17:30
  • There we go - updated. Sorry, this is only about month 3 learning ASP.NET MVC; still figuring these things out :/ – Caleb Bergman Jun 18 '12 at 17:38
  • So u r using DBContext? the good thing is u can easily cast it into ObjectContext. See the update. – VJAI Jun 18 '12 at 17:44
  • Thank you for your clear examples, I appreciate it :) Okay, nOw I'm getting the AddObject method to come up ;) Before I give it a test run, should 'surveyName' be the first parameter in the AddObject method instead of 'surveyType'? I think the first parameter is expecting a string and not a model type. – Caleb Bergman Jun 18 '12 at 17:55
2

I ended up with a slightly modified version of Mark's code:

    [HttpPost]
    public ActionResult TakeSurvey(string surveyName, FormCollection form)
    {
        //var surveyType = Type.GetType(surveyName);
        //var surveyObj = Activator.CreateInstance(surveyType);

        // Get survey type and create new instance of it
        var thisAssembly = Assembly.GetExecutingAssembly();
        var surveyType = thisAssembly.GetTypes().Where(t => t.Name == surveyName).First();
        var newSurvey = Activator.CreateInstance(surveyType);

        var binder = Binders.GetBinder(surveyType);

        var bindingContext = new ModelBindingContext()
        {
            ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => newSurvey, surveyType),
            ModelState = ModelState,
            ValueProvider = form
        };

        binder.BindModel(ControllerContext, bindingContext);

        if (ModelState.IsValid)
        {
            var objCtx = ((IObjectContextAdapter)_db).ObjectContext;
            objCtx.AddObject(surveyName, newSurvey);
            _db.SaveChanges();
        return RedirectToAction("Index", "Home");
        }

        return View();
    }

I was running into surveyType being 'null' when it was set to Type.GetType(surveyName); so I went ahead and retrieved the Type via Reflection.

The only trouble I'm running into now is here:

        if (ModelState.IsValid)
        {
            var objCtx = ((IObjectContextAdapter)_db).ObjectContext;
            objCtx.AddObject(surveyName, newSurvey);
            _db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }

When it tries to AddObject I'm getting the exception "The EntitySet name 'IntranetDb.test' could not be found." I just need to figure out to strip off the prefix 'IntranetDb.' and hopefully I'll be in business.

UPDATE
One thing I completely overlooked was passing the Model to the controller from the View...oh bother. I currently have an ActionLink replacing the normal 'Submit' button, as I wasn't sure how else to pass to the controller the string it needs to create the correct instance of Survey model:

    <p>
        @Ajax.ActionLink("Create", "TakeSurvey", "Surveys", new { surveyName = ViewBag.surveyName }, new AjaxOptions { HttpMethod = "POST" })
        @*<input type="submit" value="Create" />*@
    </p>

So once I figure out how to turn 'IntranetDb.test' to just 'test' I'll tackle how to make the Survey fields not all 'null' on submission.

UPDATE 2
I changed my submission method from using an Ajax ActionLink to a normal submit button. This fixed null values being set for my Model values after I realized that Mark's bindingContext was doing the binding for me (injecting form values onto the Model values). So now my View submits with a simple:

<input type="submit" value="Submit" />

Back to figuring out how to truncate 'IntranetDb.test' to just 'test'...

Got It
The problem lies in my IntranetDb class:

public class IntranetDb : DbContext
{
    public DbSet<Article> Articles { get; set; }
    public DbSet<ScrollingNews> ScrollingNews { get; set; }
    public DbSet<SurveyMaster> SurveyMaster { get; set; }
    public DbSet<Surveys.test> tests { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    }
}

objCtx.AddObject(surveyName, newSurveyEntry); was looking for an entry (an "EntitySet") in the IntranetDb class called "test." The problem lies in the fact that I don't have an EntitySet by the name of "test" but rather by the name of "tests" with an 's' for pluralization. Turns out I don't need to truncate anything at all, I just need to point to the right object :P Once I get that straight I should be in business! Thank you Mark and Abhijit for your assistance! ^_^

FINISHED

    //
    //POST: Surveys/TakeSurvey
    [HttpPost]
    public ActionResult TakeSurvey(string surveyName, FormCollection form)
    {
        //var surveyType = Type.GetType(surveyName);
        //var surveyObj = Activator.CreateInstance(surveyType);

        // Create Survey Type using Reflection
        var thisAssembly = Assembly.GetExecutingAssembly();
        var surveyType = thisAssembly.GetTypes().Where(t => t.Name == surveyName).First();
        var newSurveyEntry = Activator.CreateInstance(surveyType);

        // Set up binder
        var binder = Binders.GetBinder(surveyType);            
        var bindingContext = new ModelBindingContext()
        {
            ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => newSurveyEntry, surveyType),
            ModelState = ModelState,
            ValueProvider = form        // Get values from form
        };

        var objCtx = ((IObjectContextAdapter)_db).ObjectContext;

        // Retrieve EntitySet name for Survey type
        var container = objCtx.MetadataWorkspace.GetEntityContainer(objCtx.DefaultContainerName, DataSpace.CSpace);
        string setName = (from meta in container.BaseEntitySets
                                      where meta.ElementType.Name == surveyName
                                      select meta.Name).First();

        binder.BindModel(ControllerContext, bindingContext);    // bind form values to survey object     

        if (ModelState.IsValid)
        {
            objCtx.AddObject(setName, newSurveyEntry);  // Add survey entry to appropriate EntitySet
            _db.SaveChanges();

            return RedirectToAction("Index", "Home");
        }

        return View();
    }

It's kind of bloated but it works for now. This post helped me get the EntitySet from the Survey object itself so I didn't need to worry about establishing some sort of EntitySet naming convention.

Community
  • 1
  • 1
Caleb Bergman
  • 858
  • 1
  • 8
  • 18
  • @ThiemNguyen Good answer, huh? if every OP does this same-thing then no body will have interest to answer in stack overflow – VJAI Jun 19 '12 at 09:16
  • This is not a bad behavior. Please see this link: http://meta.stackexchange.com/questions/17845/etiquette-for-answering-your-own-question – Thiem Nguyen Jun 19 '12 at 10:24
  • @Mark: omg, I just took a look again at your answer and no upvote was casted yet?? I thought I've already upvoted it before, sorry for my mistake. +1 for your answer as well ;) – Thiem Nguyen Jun 19 '12 at 10:25
  • Oh, did I do something wrong? I just marked this post so it would be easier for people to pinpoint what I wound up with. I can fix it if it would make a difference :/ And thank you Thiem :) – Caleb Bergman Jun 19 '12 at 14:55
0

The main problem I see is to bind to the model to the TakeSurvey POST method. If you want different types of survey models should be handled by this method and MVC should bind to this model before calling the action, I believe you can have a wrapper model class over all such generic model, say SurveyModel and use custom model binder to bind to these models.

public class SurveyModel
{
    public string GetSurveyModelType();
    public SummerPicnicSurvey SummerPicnicSurvey { get; set; }
    public PartyAttendanceSurvey PartyAttendanceSurvey { get; set; }
}

Then write a custom mobel binder to bind this model. From the request form fields we can see what type of survey model is posted and then accordingly fetch all the fields and initialize the SurveyModel class. If SummerPicnicSurvey is posted then class SurveyModel will be set with this class and PartyAttendanceSurvey will be null. Example custom model binder.

From the controller action TakeSurvey POST method, You can update db like this:

 [HttpPost]
    public ActionResult TakeSurvey(SurveyModel survey)
    {

        if (ModelState.IsValid)
        {
            if(survey.GetSurveyModelType() == "SummerPicnicSurvey")
                _db.UpdateSummerPicnicSurvey(survey.SummerPicnicSurvey);
            else if (survey.GetSurveyModelType() == "PartyAttendanceSurvey")
                _db.UpdateSummerPicnicSurvey(survey.PartyAttendanceSurvey);

            _db.SaveChanges();
            return RedirectToAction("Index", "Home");
        }

        return View();
    }

Instead of SurveyModel encapsulating the other surveys you can have inheritance and use .net as to typecast with a check and use the Model.

Having said this, I think there is no harm in using different methods for each model. This will enable you to unit test the code well. Too many if else is not healthy to maintain. Or you can transfer the generic model SurveyModel to the repository or data access layer and let it handle that in a polymorphic way. I would prefer more small functions and keep the code clean.

Edit: The inheritance way:

    public class SurveyModel
    {      
        public virtual bool Save();        
    }

    public partial class SummerPicnicSurvey : SurveyModel
    {
      public bool Save(SummerPicnicSurvey survey)
      {
         using(var _dbContext = new MyContext())
         {
           _dbContex.SummerPicnicSurveys.Add(survey);
           _dbContex.SaveChanges();
         }
      }
    }

  [HttpPost]
  public ActionResult TakeSurvey(SurveyModel survey)
  {
     if (ModelState.IsValid)
      {
         survey.Save();
           return RedirectToAction("Index", "Home");
       }

      return View();
   }

Any new Survey model type you add has to implement the SaveChanges or Save method, Which would call the proper dbcontext method. The controller action would just call Save on the generic `SurveyModel' reference passed to it. Thus the action will be closed for modification but open for modification. The open-close design principle.

Abhijit-K
  • 3,569
  • 1
  • 23
  • 31
  • I haven't quite gotten to creating my own custom model binders in my ASP.NET MVC reading yet; I might have to check that out. I definitely **could** brute-force every check with a bunch of if--else-if statements or separate ActionMethods, but that would defeat the purpose of what I'm really going for, which is a fairly lean controller that can dynamically detect which Model it's being passed and save the form to the appropriate table. If I only had 2 or 3 surveys this might be okay, but in a few years when that number grows to 100+ it'd be a little tedious to keep updating the controller :) – Caleb Bergman Jun 18 '12 at 16:11
  • Getting rid of the if-else ais a better design. As I also said earlier you can use inheritance for the various Survey Models, each specific type of survey deriving from generic `SurveyModel`. Then encapsulate SaveChanges and dbcontext inside this SurveyModel. Any new Survey model type you add has to implement the SaveChanges or Save method, Which would call the proper dbcontext method. The controller action would just call Save on the generic `SurveyModel' reference passed to it. Thus the action will be closed for modification but open for modification. The open-close design principle. – Abhijit-K Jun 18 '12 at 17:13
  • Edited the answer post above to demo the extension design. You can implement by your own way though and how you want to inherit and which classes you want to encapsulate the save changes. The idea is to apply a extension design by moving the uncertain code as you stated in question like `_db. + typeof(survey) + .Add(survey);' to the entity which changes often. When Someone in future adds a new survey in your project he has to implement the generic survey and also some modifications in model binder. No changes to the controller. – Abhijit-K Jun 18 '12 at 17:30
  • Your method is definitely a working alternative. I may fall back on it if I can't get the system to figure out where to save the forms itself. Thank you =) – Caleb Bergman Jun 18 '12 at 19:47