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. i.e. I'd like to be able to do model.Values.Add(...)
2 Answers
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.
2 Comments
Steven
If you use the
ViewBag you will be losing the benefits of the strongly typed model as well :-)Justin Niessner
@Steven - That's my point. There's no point in trying to make your own dynamic object since there's no added benefit.
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);
}
}
5 Comments
Dmitry S.
Why would you need a multi-dimensional array to store pairs. How about public Tuple<string, int>[] Values { get { return _values; } } ?
Dmitry S.
private readonly List<Tuple<string, int>> _values = new List<Tuple<string, int>>();
Dmitry S.
The JavaScript/JSON model for the values property will look like [ { "Item1": "A", "Item2": 1 }, { "Item1": "B", "Item2": 2 } ]
Dmitry S.
Try returning Json(model, JsonRequestBehavior.AllowGet) from the controller action instead of the view to see if the model is populated properly.
Dmitry S.
If you are getting a JSON page, that is good. It means the values are populated and serialized properly. Either the model is not getting passed to the view (are you using the right View() method overload in the controller) or there is something going on with the rendering.
Valuesto be aList<string>instead ofstring[].