Home > database >  Passing item value from model to JS - MVC C#
Passing item value from model to JS - MVC C#

Time:12-02

Im working on a project with MVC and i'd like to know if there's a way to store the id of an input, which is a value received from one of my model items, into one of my JS variables

here's how the id of the input is being adressed

@foreach (var item in Model) {

<input type="hidden" value="@item.id" id="@item.id">
<input type="hidden" value="@item.nome" id="@item.nome">
<input type="hidden" value="@item.preco" id="@item.preco">

}

and here's what i been trying to do in my .JS file

var id = document.getElementById('@item.id').value;
var nome = document.getElementById('@item.nome').value;
var preco = document.getElementById('@item.price').value;

CodePudding user response:

Method 1

Well you can just expose that item ID directly to JavaScript

<script>
// this must be in the .html file, using window makes the variable global
// most rendering frameworks don't do conditional/server side rendering on static js files
window.ITEM_DATA = {
    itemId: "@item.id"
}
</script>

<input type="hidden" value="@item.id" id="@item.id">
<input type="hidden" value="@item.nome" id="@item.nome">
<input type="hidden" value="@item.preco" id="@item.preco">

Method 2

Alternatively, you can give each input a class and select all of the classes (or all of the inputs with type hidden)

<input type="hidden" value="@item.id" id="@item.id" >
<input type="hidden" value="@item.nome" id="@item.nome" >
<input type="hidden" value="@item.preco" id="@item.preco" >
// this could be in its own file because we aren't relying on the server
// this is client-side js
const [itemId, itemNome, itemPreco] = document.querySelectorAll(".item-data")
// this could also fit a narrow use case
// document.querySelectorAll("input[type='hidden']")

Edit: added clarification to method 2

CodePudding user response:

You can use css class to mark elements where you want to store the id

  1. select all elements with that css class using js
  2. read id attribute for each element using loop
  3. store it the way you need, eg. an array

CodePudding user response:

Well, if you try this you see that your values are saved.

let id = document.getElementById('Id').value;
let name = document.getElementById('Name').value;
let price = document.getElementById('Price').value;
console.log(id);
console.log(name);
console.log(price);

but i somehow fail to use them in html. This doesn't work for example.

<script>
    document.getElementById('Id').innerHTML = id;
    document.getElementById('Name').innerHTML = name;
    document.getElementById('Price').innerHTML = price;
</script>
<h1 id="Id"></h1>
<h1 id="Name"></h1>
<h1 id="Price"></h1>

It's maybe because the input is hidden.

  • Related