iko iko - 2 months ago 13
C# Question

can i use js variable as index of mvc array?

I have an array model in mvc passed to html page
I also have few divs of ".myClass" , if any of them is clicked I call function and getting their id ( each one has different integer id ) and then I want to use this id as index of an array, how can i do that? cause this code isn't working.

$(document).on('click', '.myClass', function (event) {
var id = parseInt($(this).attr('id'));
$("#Paragraph").html("@Model[id].name");
});

Answer

You cannot mix server code in js like that as the C# code will be executed on server when razor tries to render the page. Your click event happens in client side after razor sends the generated markup.

For your specific use case, first you need to read your Model and set that a local javascript array. Then you can read an item from that array.

Assuming your Model is of some collection type.

$(function(){

  //Store the Model to a local js variable.
  var myArr = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model));

  $(document).on('click', '.myClass', function (event) {
    var id = parseInt($(this).attr('id'));
    $("#Paragraph").html(myArr[id].name);
  });

});

Another option is to make an ajax call to your server where your action method accepts the unique id, using which it rebuilds the entity and send back to the client and client will use it.

Comments