How do I utilize the same variable in both JavaScript code and ASP.NET MVC Razor code?
As you can see from the code below, I created a dropdown
and filled it with data.
I want the selected item to be utilized in the below div
.
- When the user clicks on an item, what is contained within that
div
is revealed - Then the selected string item is used within the
if statement
within thediv
What currently happens is, the selected item isn't globally accessible, causing the issues you can see below.
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<div class="display-field" align="left">
<select name="mydropdown" id="mydropdown" onchange="onChange()">
@foreach (var lLMMI in lIM)
{
<option value="@lLMMI.Key.Product.PCode">
@locItem.Key.Loc.N (@lLMMI.Key.Loc.Code)
</option>
}
</select>
<br /><br />
</div>
}
var itemselected = "";
<div>
<script>
function onChange() {
var item = document.getElementById("mydropdown").value;
$('#summary').show();
}
</script>
<div id="summary">
@foreach (var lLMMI in lIM)
{
if (@lLMMI.Key.Pro.PCode == itemselected.toString())
{
<summary>extra html elements are added etc.</summary>
}
}
I can't provide you the actual code right now, but here it goes.
You have the following options for your
dropdown
.For example, you want to show
@lLMMI.Key.Product.PCode + @lLMMI.Key.Product.PName + @lLMMI.Key.Product.PAddress
. Why not load what you will show to your options' values and show them when selected? Like:And change the function to:
As others mentioned, you cannot play with Razor (server side) and Javascript (client side) like that. Think of Razor code running only once at the page load. If you want to do stuff after the page load, you need to assign your Razor variables to some client side elements and operate with client side code, JavaScript in your example.
You can't use the Javascript variable in the Razor code for two reasons:
The Razor code runs on the server to generate the page that is sent to the browser. When the page arrives to the browser it is parsed and the Javascript code runs. To use the Javascript variable in the Razor code would be a time paradox, because it would need to send the value back in time to change how the page was created, but keep the original time line in between...
There are basically two different ways of updating a page depending on input from the user: