Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8104025
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T23:43:07+00:00 2026-06-05T23:43:07+00:00

I’m attempting to create a single Controller class to handle all foreseeable surveys that

  • 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>();
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T23:43:08+00:00Added an answer on June 5, 2026 at 11:43 pm

    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 😛 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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create an if statement in PHP that prevents a single post
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
Basically, what I'm trying to create is a page of div tags, each has
I've got a string that has curly quotes in it. I'd like to replace
I have a French site that I want to parse, but am running into
I want use html5's new tag to play a wav file (currently only supported

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.