Dylan Czenski
Dylan Czenski

Reputation: 1375

ASP.NET MVC Runtime Javascript Syntax Error without error code

There is a Javascript syntax error

Form element:

@Html.DropDownListFor(model => model.UNIT, 
    new SelectList(ViewBag.UnitList, "Value", "Text"), 
    "-- Select a Unit --", 
    new {onchange = "showSelectedValue" })

Javascript:

function showSelectedValue() {
           alert('Selected: ' + @Model.UNIT); 
           // Syntax error underlines the closing parentethesis of the alert function 
        }

I want to check what UNIT is being selected with the function showSelectedValue,

Upvotes: 0

Views: 154

Answers (2)

Durga Nunna
Durga Nunna

Reputation: 51

This might help:

@Html.DropDownListFor(model => model.UNIT
    , new SelectList(ViewBag.UnitList, "Value", "Text")
    , "-- Select a Unit --"
    , new { @id = "ddUnit" });

Script:

$(document).ready(function () {
        $("#ddUnit").change(function () {
            alert($(this).val());
        });
    });

If you want to directly get the value, use this in your script:

var value = $("#ddUnit").val();

Upvotes: 1

Paul Abbott
Paul Abbott

Reputation: 7211

Razor executes server side and javascript executes client side so you can't really mix them together; your code would put the initial value of @Model.UNIT into the script as a string literal and look something like alert('Selected: ' + Whatever UNIT is);, which is a syntax error because Whatever UNIT is is not encased in quotes.

The easiest thing would be to pass the select as a parameter to the onchange function.

@Html.DropDownListFor(model => model.UNIT, 
    new SelectList(ViewBag.UnitList, "Value", "Text"), 
    "-- Select a Unit --", 
    new {onchange = "showSelectedValue(this)" })

.

function showSelectedValue(ddList) {
       alert('Selected: ' + ddList.value); 
}

Upvotes: 1

Related Questions