简体   繁体   中英

Accessing extended properties of a List class from JavaScript

I have a class which inherits from List and adds some more properties to this base class as follows:

public class MyNewList: List<string>
{
    public string MyNewProperty { get; set; }
}

I have an MVC controller which returns this kind of class:

public JsonResult GetModel()
{
    var model = new MyNewList() { "1", "2", "3" };
    model.MyNewProperty = "I want to be shown!!!";
    return Json(model);
}

My problem is that whenever I make an ajax call to server and receive this kind of class, I don't have access to MyNewProperty. It always returns undefined for MyNewProperty, but JavaScript treats the object as a list:

$http(...
    function success(result) {
        console.log(result) // ["1", "2", "3"]
        console.log(result.myNewProperty); // undefined
    }

I know that it is suggested that we should not inherit from List class but this is an existing class and logic in the project and I cannot change it. I have to find a way to send this object to JavaScript anyway.

Could anyone help me with this?

I suggest that if you change your model as given follow, we can get required result:

public class MyNewList
    {
        public List<string> data { get; set; }
        public string myNewProperty { get; set; }
    }

Controller method will be like that

 public JsonResult GetModel()
        {
            var model = new MyNewList();
            model.data=new List<string>(){ "1", "2", "3" };
            model.myNewProperty = "I want to be shown!!!";
            return Json(model);
        }

JavaScript Ajax call will be like that

  $http(...
        function success(result) {
            console.log(result.data) // ["1", "2", "3"]
            console.log(result.myNewProperty); // "I want to be shown!!!"
        }

alternately if we make some changes in Controller method without changing model structure. you can try this:

public JsonResult GetModel()
        {
            var model = new MyNewList(){ "1", "2", "3" };
            model.MyNewProperty = "I want to be shown!!!";
            var result=new {Data=model,newProperty=model.MyNewProperty};
           return Json(result);
        }

Hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM