简体   繁体   中英

How to add to array in C# dynamically

In response to this answer... Access MVC3 Model properties from Javascript in the View I'd like to know how I can construct the data for the view model in that example dynamically, without having to hardcode. ie I'd like to be able to do model.Values.Add(...)

There's already a dynamic object that you can add your values to...it's called the ViewBag .

There's no point in trying to roll your own since you're already losing the benefits of the strong typed model.

You can have a model that looks like this

public class MyViewModel()
{
    private readonly List<string> _values = new List<string>();

    public string[] Values { get { return _values.ToArray(); } }

    public void AddValue(string value)
    {
        _values.Add(value);
    }
}

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