Store the data from the form into the database according to the radio button choice

I feel like a fish out of water here...freshly dipping my toes into the ASP.net world, but finding it quite fascinating so far.

Let me begin at the starting line:

Background: I am currently working on an ASP.net MVC5 application that involves user login information. Users will be able to create accounts, receive messages, and more. The key feature is a form on the site where users can submit information using a Conditional Logic HTML Form with radio buttons, text areas, and other elements. My ultimate objective is to allow users to fill out and submit the form, save it to the MySQL database, send an email to both the admin and the user with the selected details, and display their responses in their "Account Dashboard" section.

Problem: I'm facing a challenge in extracting user-submitted information based on their radio button selection in the HTML Form, which can fall under three different scenarios:

  • Web Project
  • 2D Design Project
  • 3D Design Project

For instance, if a user selects "Web" instead of "Graphic" in the "Project Type" field, they should only be submitting values related to "Web". However, I'm uncertain about the best approach to tackle this issue...

Here's a snippet of the code I've started working on for when a user chooses a Web project for submission to the database:

if (IsPost) && (RadioButton.projectType.Equals(Web))
{
    projectType = Request.Form["Web"];
    TypeOfWebsite = Request.Form["TypeOfWebsite"];
    DeviceExperience = Request.Form["DeviceExperience"];
}

Below are the form values:

<form method="post">
        <br />

        <!--Form fields go here-->

    </form>

I have referred to various MSDN tutorials to gain a better understanding:

However, these resources haven't provided clear guidance on how to implement the three conditional statements necessary for my form:

  • "If user selects Project Type = "Web" and submits the form, save the data to the database"
  • "If user selects Project Type = "Graphic" and Dimension = "2D" upon form submission, store the relevant values"
  • "If user selects Project Type = "Graphic" and Dimension = "3D" when submitting the form, save the corresponding values to the database"

Recap:

  • How do I write the conditional statement to achieve this?
  • Should I reconsider the HTML form structure I'm currently using in favor of ASP Web Pages?

I have also implemented some JavaScript to dynamically display available form values based on user selections. It's functioning as expected! I now need assistance in linking this information to the database for user profile usage. Any insights or solutions would be greatly appreciated!

Answer №1

This is quite a complex form, but I'll simplify it for you by reducing the number of fields to demonstrate the MVC approach.

It seems like you're not fully utilizing MVC (Model-View-Controller) in your code. Models play a crucial role in MVC architecture, so it's recommended to include them in your project. Let's consider the following models...

public class ProjectTypeModel
{
    public string Name { get; set; }
}

public class TestModel
{
    public IList<ProjectTypeModel> Types { get; set; }
}

Your view should reference these models at the top of the file, like this...

@model  MvcTest.Models.TestModel

Now, let's simplify the form design with the following structure...

@using(Html.BeginForm("ProcessTypes","Home")){
    <div class="row">
        <label class="formquestion col-md-3">Project Type: </label>
        <span class="col-md-8">

            @foreach (var p in Model.Types)
            {
                <input id="@("radio_" + p.Name)" type="radio" name="SelectedProjectType" value="@p.Name" />
                <label for="@("radio_" + p.Name)">@p.Name</label>
            }

        </span>

    </div>

    <input type="submit" name="SubmitForm" class="btn btn-info btn-large" value="Submit Form" />
    }

Just ensure that radio buttons share the same name attribute and have unique ids for label association. The form submits data to the "ProcessTypes" action in the Home controller...

Your Home controller's action might look like this...

public ActionResult ProcessTypes(string SelectedProjectType)
        {

            // processing logic...
       }

In this simplified example, the SelectedProjectType variable will hold the selected radio button value ("Web" or "Design"). This overview should give you a basic understanding of MVC and Razor syntax. There's more to explore, so keep learning!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Would you mind providing some clarification on these two JavaScript examples?

1: The result of foo && baz is not 1 because true equals to 1 in numerical terms. var foo = 1; var baz = 2; foo && baz; // returns 2, which is considered as true 2: In the expression console.log(foo + +bar);, the two plus signs have a ...

Error: The module cannot be found due to a resolution issue when trying to import the Vue.js component './app/index.vue' using ES6 syntax

I am currently in the process of learning how to use webpack2 with vue.js and babel. However, I've encountered an error that I can't seem to resolve. I'm not sure what exactly is missing. ERROR in ./src/main.js Module not found: Error: Can ...

Adding the Load More feature to your WordPress template for displaying custom posts

On my website, I am retrieving posts of a custom post type using get posts. However, I am retrieving all posts at once, but in my template, I want to display x number of posts per page and load the remaining posts using a load more button. <?php ...

How are single and double quotation marks utilized in SQL databases?

When passing a string or number to a SQL query, I often see single quotes and double quotes used together. What is the significance of having both? select * from college where class = '"+txtclass.Text+"' or select * from college where class = ...

Tips for creating a stylish ReactJs Header component that stays fixed at the top of the page

Having an issue with my Header component - I want it to remain fixed at the top while scrolling down. Here's the current code: I've attempted using "position = fixed", but it caused my header to resize. Then, I tried setting its width to "width ...

How can I create a new PHP table using data from an existing table?

I have a table displayed on my website with the code snippet providedview the table image here Here is the code for generating this table: <?php $query = $db->query("SELECT * FROM bit_exchanges ORDER BY id DESC LIMIT 20"); if($query-> ...

Ways to access Angular controllers from various folders

Yesterday, I dove into learning my first node.js/MEAN application and stumbled upon this helpful tutorial to kick-start my journey: https://scotch.io/tutorials/creating-a-single-page-todo-app-with-node-and-angular After following the tutorial and successf ...

Challenges encountered when trying to save a json document

I have a function that successfully connects to an API and retrieves particle, name, and community_price data for various items. Now, I want to save this data into a JSON file with the following structure: [ { "particle": "xxx", "name" ...

jQuery is not active on responsive designs

I have implemented a script in my JavaScript code that changes the color of the navigation bar when scrolling. The navigation bar transitions to a white color as you scroll down. However, I am facing an issue with responsiveness and would like to deactivat ...

Using TypeScript and webpack 2 to integrate typeahead.js into your project

I am encountering an error message coming from webpack. ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts Module not found: Error: Can't resolve 'typeahead' in ... I have the following dependencies installed npm install ...

Trouble with linkage in jQuery for AJAX requests in an external .js document

My asp.net application has a master file that includes the jquery.js file. On another page that uses this master page, I have my own jquery code. I attempted to move this code to an external file and then include it in my .aspx file. While most functions ...

The exception ResourceClosed is being thrown by my servlet

I am experiencing an issue with my servlet where three devices are trying to access the result simultaneously. The problem is that the first device usually displays the result, the second sometimes does, but the third device consistently receives a 500 i ...

Enzyme fails to locate text within a div even though it is present

In my current test scenario, I have a set of data displayed in Material-UI Cards. The data is provided through a JSON array consisting of objects with fields like projectName, crc, dateCreated, createdBy, and lastModified. { projectName: 'P ...

How can I retrieve a formController in AngularJS?

When trying to reset the data in a form and calling form.setPristine(), I encounter an issue where the formController is not registered within the $scope. It may sound like a basic question, but how can I locate the formController? Within the code snippe ...

Can't seem to res.send using Express framework

Hello, I'm encountering an issue when trying to send a response using Express. I've seen suggestions in other questions that changing the variables err and res may resolve this problem, but it hasn't worked for me. router.post('/checkP ...

CSS transition fails to revert

My standard opacity animation is not working in reverse order. Here is a link to the JSFiddle example. According to the documentation, it should work automatically. Since I am new to JavaScript, I am unsure if this issue lies in my code or if the CSS anima ...

Tips for setting react-native image source dynamically in a flat list

As a beginner in react native, I'm attempting to populate a flat list with images that are stored within the app. My goal is to dynamically set the image source in each iteration. This is my current approach, but I'm in need of assistance. <F ...

Exploring the variations between getRequestHandler and render functions in Custom Next.js applicationsIn a

Greetings, I found it quite unexpected that there is a lack of information available on the functionalities of the getRequestHandler and render functions within the next package. As I am in the process of setting up a custom server, I am curious about wh ...

At what precise scenarios do synchronous continuations pose a risk?

In a blog post, Sergey Tepliakov from Microsoft emphasizes the importance of always including TaskCreationOptions.RunContinuationsAsynchronously when creating TaskCompletionSource instances. However, there seems to be some confusion as he also mentions t ...

Having trouble with my ajax request not functioning correctly

<body style="margin:0px; padding:0px;" > <form method="post" > <input type="text" id="city" name="city" placeholder="Enter city name"> <input type="submit" value="Search City" id="searchid"/> ...