2

I get the following error, "ReferenceError: Cat is not defined", when trying to pass a model to view and print out it's text value with JavaScript. Why is there a reference error and how to fix it?

Model:

public class Animal
{
    public List<SelectListItem> AnimalList { get; set; }

    public Animal()
    {
        SelectListItem animalItem = new SelectListItem();
        animalItem.Text = "Cat";
        animalItem.Value = "1";

        AnimalList = new List<SelectListItem>();
        AnimalList.Add(animalItem);
    }
}

Controller:

    public ActionResult Index()
    {
        var model = new Animal();

        return View(model);
    }

View:

<script type="text/javascript">
$(document).ready(function () {
    @foreach (var item in Model.AnimalList)
    {
        <text>
            console.log(@item.Text);
        </text>
    }
});
</script>

By the way. It works fine if I set the text to a number, for example 0.

1
  • 1
    Put it between quotes: '@item.text' Commented Nov 7, 2012 at 19:18

1 Answer 1

3
<text>
    console.log("@item.Text");
</text>

Need quotes around the @item.Text.

JS is thinking you want a variable cat, when you want a string "cat"

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

2 Comments

This is such an odd answer to downvote after 3 1/2 years. If @downvoter cares to elaborate, it would be appreciated.
And tbh it solved the problem for me (8 years after), so don't understand why downvoting ^^

Your Answer

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