5

I'm working on an MVC 5 project and I have two datalist. One holds a list of documents and the other holds formatting information. What I'm trying to achieve is when I select one of the documents the format list would then be filtered down to what applies to that document. So my thought with this was to take my @Model.documents and store it to an array so I could look for the doc id.

 <input list="doc" id="document" />
                    <datalist id="doc" name="Doc" placeholder="Please select a document type">
                        @foreach (var item in Model.docType)
                        {
                            <option id="@item.DocumentTypeID" value="@item.DocumentTypeName"></option>
                        }
                    </datalist>

<input list="tribute" />
                    <datalist id="format">
                        @foreach (var item in Model.format)
                        {
                            <option value="@item.formatName"></option>
                        }
                    </datalist>

$(document).ready(function () {
        $('#document').change(function () {
            var x = $("#doc option[value='" + $('#document').val() + "']").attr('id');

            var trib = [];

            @foreach (var d in Model.documents)
            {
                @:trib.push("@d");
            }
            console.log(trib);
        });
    });

However, this is just putting into the array as Model.documents which I believe is due to it having multiple columns. Any help is appreciated thank you!

2
  • 1
    You might want to look at serializing into JSON. JavaScript could then read it. Commented Dec 23, 2019 at 19:15
  • @the_lotus I was thinking about that, but the server we have is able to to use the for json command and I wasn't sure if using converting it from its current format to json using C# was an efficient method. Commented Dec 23, 2019 at 19:20

2 Answers 2

8

Convert your C# list to js array and use it inside of "change" event:

var jsArray = @Html.Raw(Json.Encode(Model.documents));
Sign up to request clarification or add additional context in comments.

1 Comment

This is a really, really nice trick! I used to use string.Join for that but this is so much better!
0

Your passing C# object (server side) into JS array (client). All you will get is type name in the array.

See if you can add document type as class name for format type options. so that based the document selection you can filter the format options with respective document type class only. you can do this filtering using javascript

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.