简体   繁体   English

从JavaScript访问List类的扩展属性

[英]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: 我有一个继承自List的类,并为这个基类添加了一些属性,如下所示:

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

I have an MVC controller which returns this kind of class: 我有一个MVC控制器返回这种类:

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. 我的问题是每当我对服务器进行ajax调用并接收这种类时,我都无法访问MyNewProperty。 It always returns undefined for MyNewProperty, but JavaScript treats the object as a list: 它始终为MyNewProperty返回undefined,但JavaScript将对象视为列表:

$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. 我知道我们不应该继承List类,但这是项目中现有的类和逻辑,我不能改变它。 I have to find a way to send this object to JavaScript anyway. 我必须找到一种方法将此对象发送到JavaScript。

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 JavaScript Ajax调用将是这样的

  $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. 或者,如果我们在不改变模型结构的情况下对Controller方法进行一些更改。 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. 希望它会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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