How can I pass the current value of an HTML.DropDownListFor to an ActionLink?

Is it feasible to transfer the current value of @Html.DropDownListFor to an action link? I am trying to send the template value to the Sample controller using the Create action. The code below is not functioning because @Model.SurveyTemplate does not return any value. Do I need to use JavaScript to retrieve it? Any guidance would be appreciated.

Dropdown List:

@Html.LabelFor(model => model.Survey_Template, "Survey Template")
                @Html.DropDownListFor(model => model.Survey_Template, new SelectList(
                  new List<Object>{
                       new { value = "Style1" , text = "Style1"  },
                       new { value = "Style2" , text = "Style2" },
                       new { value = "Style3" , text = "Style3"}
                    },
                  "value",
                  "text",
            0))

ActionLink:

@Html.ActionLink("_", "Create", "Sample",
            new { template = @Model.Survey_Template },
            new { @id = "popup-link", @class = "classname2" })

Answer №1

To achieve this task, you will need to utilize JavaScript as the razor syntax is only recognized on the server side. This means that @Model.Survey_Template will be displayed when the user requests the page and will contain the default value.

If you opt to use JavaScript, remember to store the base URL and add parameters based on the user's selection.

Follow these steps to reach your desired outcome:

  1. Assign a change event to your dropdown.
  2. Extract the selected value and create a new URL.
  3. Update the URL (href) of the action ()

Note: I have not provided the code to encourage you to challenge yourself.


I believe you are aiming for a form with GET method.

@using(Html.BeginForm("Create", "Sample", FormMethod.GET)){
    @Html.LabelFor(model => model.Survey_Template, "Survey Template")
    @Html.DropDownListFor(model => model.Survey_Template, new SelectList(
        new List<Object>{
           new { value = "Style1" , text = "Style1"  },
           new { value = "Style2" , text = "Style2" },
           new { value = "Style3" , text = "Style3"}
        },
        "value",
        "text",
    0))

    <input type="submit" value="_" class="classname2" id="popup-link" />
}

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

How to Save Checkbox Selections in the Order They Were Clicked Using PHP

I have a form with 4 checkboxes, and I need to save the selected checkboxes in the database in the order they are clicked. For example, if the checkboxes are clicked in the sequence 1, 3, 4, 2, then they should be saved in the database in that exact order. ...

Jquery animate - callback is triggered before animation finishes running

Is there a way for the element to first expand in height and then apply a background image once the height change is complete? Currently, I am experiencing laggy performance as the background image is applied before the height animation finishes. Can som ...

Sometimes an InvalidElementStateException or ElementNotVisibleException may occur while attempting to interact with an input field using SendKeys

I am currently working on a code that looks like this: IWebDriver driver = new FirefoxDriver(); driver.Manage().Window.Maximize(); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(30)); //Go to the powerbi site driver.Navigate().GoToUrl("htt ...

Issue with updating input value during keyup event in Android Chrome specifically

Check out this straightforward jsfiddle: https://jsfiddle.net/gq9jga4q/33/ <input type="text" id="kbdhook" /> <div id="result" >1: </div> <div id="result2" >2: </div> <div id="result3" >3: </div> $('#kbdh ...

Sending a HttpPostFileBase request from an MVC view using Ajax

I am currently dealing with a form that involves uploading a file. Everything is working fine, with the form post controller checking for the existence of a file with the same name in the database. If a file with the same name exists, it passes the HttpPos ...

Tips for capturing the current terminal content upon keypress detection?

After successfully installing the terminal on a test page, I am looking to highlight matching parentheses within it. This is similar to what is done in this example: I have a working solution in place and now need to integrate it with the terminal. ...

Running system commands using javascript/jquery

I have been running NodeJS files in the terminal using node filename.js, but now I am wondering if it is possible to execute this command directly from a JavaScript/jQuery script within an HTML page. If so, how can I achieve this? ...

Updating the value of each preceding sibling of every checked checkbox using jQuery upon form submission

After extensive research, I discovered that the most effective approach involves using a clever workaround to capture every tick and untick on a dynamic input row with multiple checkbox arrays. However, none of the solutions provided a viable method. I th ...

Remove all of the classes from the specified element using JavaScript

I have a button and I want to remove all the classes when it is clicked. Here is what I have tried: button.style.className = '' document.querySelector('button').onclick = function() { this.style.className = ''; } .myClas ...

jsTree unable to locate node using the provided ID

Implementing the jsTree on the webpage is not a problem for me. I have experimented with numerous suggestions from different sources. $('#myTree').jstree({ .... }) .on('loaded.jstree', function (e, dta) { var t = $('#myTree&a ...

Listening for TFS subscription events using an event listener in C#

My goal is to develop a C# application that will execute specific code whenever a build is completed on a TFS/VSTS server. I admit I am not very experienced in using event listeners in C# or subscriptions in TFS/VSTS, but hopefully someone out there is. A ...

What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue. I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav ...

Beginner's guide to using Express: a step-by-step tutorial on making API requests from client-side JavaScript to

Currently, I am immersed in a Javascript project where I utilize the Nasa Mars Rover API and Immutable Js to creatively display images and information on my webpage. By harnessing the power of pure functions and functional programming, I maintain app state ...

"Troubleshooting: Why is TailwindCSS not functioning correctly in my NextJS

My project utilizes a combination of NextJS, TailwindCSS, and Typescript. Strangely, everything displays correctly in the development environment, but once in production, the tailwindcss classes are not being applied. For reference, here is the link to t ...

Whenever I launch my React web application, I consistently encounter a white screen when attempting to access it on my phone

After developing my web app in ReactJS and deploying it to the server, I've noticed that sometimes the screen appears white for the first time after deployment. However, when I reload the page, the app runs normally. I am hosting the backend and front ...

Basic jQuery request for JSON data

In an effort to send user data to a PHP script and display the results in an element, I am utilizing JSON. The process works smoothly until reaching the response stage. Despite receiving the correct results when logging to the console, attempting to append ...

Revolutionizing Form Select Field: Introducing Rails' Dynamic Input Rendering

I'm a beginner in coding, so please bear with me if my question sounds amateurish. Currently, I am developing an e-commerce website where customers can order posters from images uploaded to the site. They should be able to choose the size of the poste ...

JavaScript: Modifying an Array of Matrices

Could anyone assist me with updating a matrix array? I have an initial matrix with preset values and need to update specific coordinates within it. Here is the base matrix: var myMatrix = [ ['-','-','-','-',&ap ...

Tips for embedding a file within a text box in HTML and enabling users to make direct edits

I am currently working on a feature that allows users to open a .txt or .html file from their file explorer and paste the contents into a textarea for editing and saving purposes. My question is whether it's possible to read the file content and auto ...

Add unique content to a div upon page reload

Whenever the page is refreshed, I would like to add a random anchor from an array into a specific div. Here's my current code: <div id="exit-offer" class="exit-offer-dialog"> <div class="offer-content" id="banner-load"> <bu ...