Showing the `ViewBag` data within the `@Html.DropDownListFor` method enclosed

I'm currently working with a DropDownListFor that is set up like this:

        <div class="form-horizontal" id=CurrencyDataBlock>
            @Html.DropDownListFor(model => model.Code, ViewBag.Currency as SelectList, "--Select Currency--", new { @class = "btn btn-default col-xs-12 col-xs-offset-0 col-sm-2" })
        </div>

In my JavaScript function, I am creating a container and fields. To pass the entire container within single quotes, I do it like this:

    var part1 = '<br><br><hr style="height:1px;border:none;color:#333;background-color:#333;" /><div><input type="button" class="btn btn-default" onclick="ReTextBox(this)" value="Remove"/></div><textarea rows="10" cols="100" id="Text" name="dyntxt" style="width: 550px; height: 125px; margin-left: auto;"></textarea>'

However, I encounter an issue when trying to pass a ViewBag (from the initial setup) into single quotes. I attempted it like this:

var part3 ='<div class="form-horizontal" id=CurrencyDataBlock>@Html.DropDownListFor(model => model.Code, ViewBag.Currency as SelectList, "--Select Currency--", new { @class = "btn btn-default col-xs-12 col-xs-offset-0 col-sm-2" })</div>'

I also tried alternatives like: @ViewBag.Currency

And: '@ViewBag.Currency'

But nothing seems to be successful. The first option results in an error: "ReferenceError: DynamicText is not defined". The second attempt produces the same error. When attempting to use single quotes directly, it doesn't even compile and shows an error like: struct System.Char - Represents a character as a UTF-16 code unit. Too many characters in character literal

Finally, I experimented with this approach: I also tried this (idea):

var part3 ='<div class="form-horizontal" id=CurrencyDataBlock>@Html.DropDownListFor(model => model.Code, ViewBag.Currency.Replace("\\", "\\\\").Replace("'", "\\'") as SelectList, "--Select Currency--", new { @class = "btn btn-default col-xs-12 col-xs-offset-0 col-sm-2" })</div>'

This method compiles without errors, but the page fails to load.

Any suggestions or ideas?

Answer №1

These are my suggestions for you:

To avoid issues with single quotes, try using backticks (`) instead. This way, you can write your HTML code without worrying about single or double quote conflicts.

I noticed a possible typo in your HTML where you have id=CurrencyDataBlock.

var part3 = `<div class="form-horizontal" id="CurrencyDataBlock">
                @Html.DropDownListFor(model => model.headline, ViewBag.Currency as SelectList, "--Select Currency--", new { @class = "btn btn-default col-xs-12 col-xs-offset-0 col-sm-2" })
            </div>`;

var part1 = `<br><br>
                <hr style="height:1px;border:none;color:#333;background-color:#333;" />
                    <div><input type="button" class="btn btn-default" onclick="ReTextBox(this)" value="Remove"/></div>
                    <textarea rows="10" cols="100" id="Text" name="dyntxt" style="width: 550px; height: 125px; margin-left: auto;"></textarea>`;

When passing lists, it's helpful to use

@Html.Raw("your list or other variables here")
.

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

Create a custom loading spinner for a jQuery AJAX request

How can I add a loading indicator to my Bootstrap modal that is launched from a link? Currently, there is a 3-second delay while the AJAX query fetches data from the database. Does Twitter Bootstrap have built-in functionality for this? UPDATE: Modified J ...

How can the ID of a table row be retrieved if it is selected?

In my datatable, I have a list of Cars where each row contains a Car ID. A checkbox column has been added to the first cell in the table - when checked, the row is highlighted to show the user their selection. The goal is to retrieve the IDs of all selecte ...

Ways to obtain the ID of the following element using jQuery

Here is some HTML code, and I am trying to retrieve the ID of the next element from a clicked element with the class name "coba" or to get the ID of an element with the class name "coba2." <div class="dropdown"> <label>Category</label> ...

Showing the Length of Several Videos Simultaneously on a Webpage

I am attempting to showcase the "duration" for each video on the page using JavaScript. This is my current code: var vid = document.querySelector(".mhdividdur"); vid.onloadedmetadata = function() { var x = document.querySelector(".mhdividdur").duratio ...

Warning: Neglecting to handle promise rejections is now considered outdated and discouraged

I encountered this issue with my code and I'm unsure how to resolve it. DeprecationWarning: Unhandled promise rejections are deprecated. In the future, unhandled promise rejections will terminate the Node.js process with a non-zero exit code. This ...

I am currently facing an issue in my Node.js environment specifically with the 'oracledb' package

I am encountering an issue with the oracledb modules. Fortunately, I was able to successfully install oracledb. When I run the command like this, -> npm install oracledb njsOracle.cpp njsPool.cpp njsConnection.cpp njsResul ...

"Utilizing jQuery to Send POST Requests on Rails - Dealing

Currently, I am running a JavaScript game from file:// and attempting to send a post request to a localhost Rails server in order to add a new high score. In my JavaScript: highScoresEntryView.keyHandlers = function() { var that = this; this.pa ...

Guide to adding customized CSS and JavaScript to a specific CMS page on Magento

I'm trying to incorporate a lightbox for video playback on a specific page of my CMS. I've placed my CSS file in JS/MY THEME/JQUERY/PLUGIN/VENOBOX/CSS/myfile.css and the JS files in JS/MY THEME/jquery/plugins/venobox/js/myfile.js, but it doesn&ap ...

Tips for displaying Vue Components on an HTML5 canvas surface

How can I incorporate an htmlcanvas as the webpage background and overlay Vuejs components on top of it? I know the answer must exist, but I'm not sure where to start looking. ...

Substitute dynamic Angular expressions with fixed values within a string

Inside my angular controller, I am defining a stringTemplate containing expressions like "{{data.a}} - {{data.b}}". Along with that, I have an object named data with values {a: "example1", b: "example2"}. My goal is to find a way to replace the dynamic ex ...

Transfer information through the react-native-ble-plx module

To initiate a project involving connected devices, I must establish a Bluetooth connection among the different devices. The objective is to develop an application using React Native and then transmit data from this application to my Raspberry Pi. The Rasp ...

Adjusting the font color when hovering over multiline text

I am currently in the process of coding a website for my job, and I am working on changing the text color when it is hovered over. However, there seems to be a break in my code causing the text not to highlight all at once. Any guidance or suggestions on h ...

Is there a way to dynamically apply the "active" class to a Vue component when it is clicked?

Here is the structure of my Vue component: Vue.component('list-category', { template: "#lc", props: ['data', 'category', 'search'], data() { return { open: false, categoryId: this.category ...

JavaScript: Creating a Function that Returns an Object with an Undefined `this.variable`

While using javascript, I encountered an issue with instance variables. Declaring a variable as "this.variable" works fine until my function returns an object. However, if the function returns a String or Number, there are no issues. But when it returns ...

Managing Chrome application authentication pop-up with Selenium Webdriver and C#

https://i.sstatic.net/lPbCv.png I have come across numerous discussions on this matter but none of the solutions seem to be effective. I am looking for a way to input the username and password into the chrome authentication alert using Selenium Webdriver ...

Error encountered: API key is required - Issue found in: /node_modules/cloudinary/lib/utils.js at line 982

I encountered an issue with cloudinary while trying to upload photos on my website after adding a new function for Facebook login. "/home/ubuntu/workspace/YelpCamp/node_modules/cloudinary/lib/utils.js:982 throw "Must supply api_key"; ^ Mus ...

Focus event in IE does not always work as expected after an ajax request is

Our current focus is on supporting IE8 exclusively. An ajax call retrieves data from the server, replaces the HTML in a container div with the response, and then attempts to focus on an element within the response. However, there seems to be inconsistenci ...

Add navigation dots to the slider in order to align them with the specified div element

Visit this JSFiddle link for the code <html> <link href="./style.css" rel="stylesheet" type="text/css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script&g ...

Guide on managing firebase and webrtc tasks within a client-side component using Next.js 13

I developed a Next.js 13 application to share the camera feed using WebRTC and Firestore. Below is my page.tsx file where I am facing some challenges. I can't make this server-side because I'm using React hooks, and moving it to the client side i ...

Ways to merge values across multiple arrays

There is a method to retrieve all unique properties from an array, demonstrated by the following code: var people = [{ "name": "John", "age": 30 }, { "name": "Anna", "job": true }, { "name": "Peter", "age": 35 }]; var result = []; people. ...