0

I'm trying to update a database driven program to MVC5. My current hurtle is a simple selection list. I have it printing out values and taking data just fine, but it needs to default to the currently stored value when the user opens the modal it is contained in.

View code snippet:

    <select ng-model="DbReferenceId">
    @foreach (var item in (ViewData["ReferenceData"] as List<Reference>))
        {
            <option value="@item.Id">@Html.DisplayFor(modelItem => item.IdDisplay)</option>
        }
    </select>

So we're all on the same page, DbReferenceId is the current value of Reference, and item.Id/IdDisplay point to possible options for Reference from another table.

So, what's a quick and dirty way I can get this working?

UIDAlexD
  • 218
  • 2
  • 12
  • 1
    The *not so "quick and dirty" way* to do this would be to have a view model that your view uses, with a property on there of `List` (populated from your controller with Db values). Then, in your view you can use the `@Html.DropDownListFor()` helper to create this list, and you can then give the `ng-model` attribute using an anonymous `HtmlAttributes` dictionary. I can elaborate in an answer - but you asked for "quick and dirty", so I'm reluctant to – Geoff James Jul 19 '16 at 15:04
  • Well I'd prefer something minimal but I prefer take a larger solution over none at all. Please go on. – UIDAlexD Jul 19 '16 at 15:07
  • could you provide the generate html by the above razor syntax? – Deep Jul 19 '16 at 15:22
  • OK. So minimal would be: store the default/stored value in a variable in JS, somewhere when the page is loaded e.g. `var defaultVal = '@theValue';` < note to enclose the value in `'`s for JS. Then, you can find and select the default value, from that ` – Geoff James Jul 19 '16 at 15:26
  • Any way to do that without using JQuery? – UIDAlexD Jul 19 '16 at 17:32
  • Yes, using JavaScript. It's the same principle as jQuery, just a bit more verbose: You still set a local variable the same way (`var defaultVal = '@theDefaultValue'`), then add an event handler for your button - `document.getElementById(someButton).addEventListener('click', function() {...});`. In the callback (`function() { ... })` change the value of your select - `document.GetElementById('yourSelect').value = defaultVal;`; and then open your modal – Geoff James Jul 21 '16 at 10:09

0 Answers0