How to pass an object from a link to a function
Environment is MVC with jQuery. I built a cut down example to show my problem:
From my web page I consume getDogs from my Controller:
- public ActionResult getDogs()
- {
- List<Dog> myDogs = new List<Dog>();
- Dog d = new Dog();
- d.dogName = "Doc";
- d.dogBreed = "Many";
- myDogs.Add(d);
- d = new Dog();
- d.dogName = "Sadie";
- d.dogBreed = "Boston Terrier";
- myDogs.Add(d);
-
- return Json(myDogs);
- }
In my page, using jQuery.each, I create a list of links showing each dogs name. In the on click of the link I want to pass the dog object into a function where I would access the dogName property. For this example I just alert it. The message I get is undefined. I know how to pass individual properties both singular and multiple to a function. I can't seem to pass the object.
Thanks!
- <script>
- $(document).ready(function () {
- getDogs();
- });
- function getDogs() {
- var myUrl = ' /ScratchPad/getDogs/ ';
-
- $.post(myUrl, null, function (data) { landGetDogs(data); }, 'json');
- }
- function landGetDogs(x) {
- $('#dogs').empty();
- jQuery.each(x, function () {
- $('#dogs').append("<li style='font-size:10px;margin:0;padding:0;margin-left:40px;list-style:none' ><a href='#' onclick='viewDog(" + '"' + this + '"' + ")'>" + this.dogName + "</a></li>");
- });
- }
- function viewDog(x) {
- alert(x.dogName);
- }
- </script>