Ad

Razor Inline If Statement In Javascript

- 1 answer

I need to write an inline razor if statement to set selected value of dropdownlist in javascript like this:

$.each(response,
    function (key, value) {
        $(Banner).append($("<option @(dataUi != null && dataUi.Fk_BannerId == value.Id ? "selected=\"selected\"" : "") value="
                        + value.Id + ">"
                        + value.Name + "</option>"));           
    }
);

but is says can not resolve symbol value how can I use value.Id in this razor if statement?

Ad

Answer

I'm writing this blind so please forgive any typo's.

Try something like this:

<script>
$.each(response, function (key, value) {
    var _dataUiID = "@dataUi.Fk_BannerId";
    var _selected = "";
    if(value.Id == _dataUiID) {
        _selected = "selected='selected'";
    } 
    $(Banner).append($("<option " + _selected + " value="
        + value.Id + ">"
        + value.Name + "</option>"));
    });
</script>

Sorry, not sure if dataUi.Fk_BannerId is numeric or a string so you may have to adjust var _dataUiID = "@dataUi.Fk_BannerId"; a little...also to cater for null...

Ad
source: stackoverflow.com
Ad