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?

8
  • stackoverflow.com/a/13652417/1731706 Commented Aug 10, 2015 at 15:46
  • @daniel Are you saying this is impossible? Commented Aug 10, 2015 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? Commented Aug 10, 2015 at 15:49
  • check the link again :) Commented Aug 10, 2015 at 15:49
  • @nurdyguy The error is "The name 'text' does not exist in the current context. Commented Aug 10, 2015 at 15:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

No, the dictionary is not just <int, string>, but <int, SomeComplexObject>.
You should be able to access it from your JavaScript object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.