0

In my Model, there is a dictionary named Feeds. I need to access a particular item in Feeds from javascript code:

 var feedID = $sourceRow.attr('id');
 var jobDescriptionMaximumLength = @Model.Feeds[Convert.ToInt32(<text>feedID</text>)];

This doesn't work. Could you please what I am doing wrong and what would be the right approach?

tereško
  • 58,060
  • 25
  • 98
  • 150
  • http://stackoverflow.com/a/13652417/1731706 – daniel Aug 10 '15 at 15:46
  • @daniel Are you saying this is impossible? – Dmitriy Reznik Aug 10 '15 at 15:48
  • Can you say more than "This doesn't work"? Can you add a debugger and step through it and see what happens? – nurdyguy Aug 10 '15 at 15:49
  • check the link again :) – daniel Aug 10 '15 at 15:49
  • @nurdyguy The error is "The name 'text' does not exist in the current context. – Dmitriy Reznik Aug 10 '15 at 15:56
  • @daniel Can you clarify how that approach can be applied? I tried this without success: var jobDescriptionMaximumLength = @Model.Feeds[Convert.ToInt32("feedIDVar")]; jobDescriptionMaximumLength = jobDescriptionMaximumLength.replace("feedIDVar", feedID); – Dmitriy Reznik Aug 10 '15 at 16:06
  • The smoking gun in his case is the actionlink: http://www.c-sharpcorner.com/UploadFile/abhikumarvatsa/ajax-actionlink-and-html-actionlink-in-mvc/ – daniel Aug 10 '15 at 16:08
  • I figured it was something along those lines. It just means it is trying to read 'feedID' as javascript instead of as part of the razor. Try one of the syntaxes here: http://stackoverflow.com/questions/4599169/using-razor-within-javascript – nurdyguy Aug 10 '15 at 16:10

1 Answers1

0

One thing you can do is to assign the dictionary (your Feeds Property value) to a javascript variable and then you can access it in your client side script.

If your Feeds property is of type Dictionary<int,string>, you will get something like this in your feeds property.

{1: "StringVal1", 2: "StringVal2"}

From this javascript object, you can access your dictionary item value using the key.

Code for your razor view will be

@using Newtonsoft.Json
@model YourNameSpaceHere.YourViewModelTypeHere

<script type="text/javascript">

    $(function() {

     var feeds = @Html.Raw(JsonConvert.SerializeObject(Model.Feeds));

     console.log(feeds);

     var feedId = 2; // replace with real value to check
     alert(feeds[feedId]);
    });
</script>

Alternatively , you may consider making an Ajax call with the feed id to an end point which returns the complex object you want.

Shyju
  • 214,206
  • 104
  • 411
  • 497