When calling a javascript function, it only works if I pass in an int. It fails if I pass in a string.
For example, this is my controller where I’m passing in a list of people to the view.
public ActionResult Index()
{
List<Person> people = new List<Person>();
people.Add(new Person() { Id = 1, FirstName = "Geddy", LastName = "Lee" });
people.Add(new Person() { Id = 2, FirstName = "Alex", LastName = "Lifeson" });
return View(people);
}
In the view, I have this javascript function:
function RemovePerson(firstName) {
alert(firstName);
}
My webgrid has a column that allows the user to delete a person:
gridPeople.Column(header: "", columnName: "",
format: (person) => MvcHtmlString.Create(string.Format(
"<a href='' onclick='RemovePerson({0}); return false;'>x</a>",
person.FirstName))),
As the code is shown, above, I get this error when I click the x to delete a person:
Uncaught Reference Error: Geddy is not defined
Why?
If I change the javascript to accept an int:
function RemovePerson(personId) {
alert(personId);
}
And actually pass the int:
gridPeople.Column(header: "", columnName: "",
format: (person) => MvcHtmlString.Create(string.Format(
"<a href='' onclick='RemovePerson({0}); return false;'>x</a>",
person.Id))),
It correctly shows a message box with the int value. So why does this work when passing an int but not the name?
The reason is that you need to wrap the string variable in quotes.
That means it thinks you’re referring to a variable named
Geddyrather than the string literal"Geddy".Here’s what you use: