Reputation:
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.
Upvotes: 2
Views: 2566
Reputation: 2414
<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"
Upvotes: 3