0

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(...)

1
  • 3
    Change the Values to be a List<string> instead of string[]. Commented May 9, 2012 at 19:35

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If you use the ViewBag you will be losing the benefits of the strongly typed model as well :-)
@Steven - That's my point. There's no point in trying to make your own dynamic object since there's no added benefit.
1

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

Why would you need a multi-dimensional array to store pairs. How about public Tuple<string, int>[] Values { get { return _values; } } ?
private readonly List<Tuple<string, int>> _values = new List<Tuple<string, int>>();
The JavaScript/JSON model for the values property will look like [ { "Item1": "A", "Item2": 1 }, { "Item1": "B", "Item2": 2 } ]
Try returning Json(model, JsonRequestBehavior.AllowGet) from the controller action instead of the view to see if the model is populated properly.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.