The Angry Saxon
The Angry Saxon

Reputation: 792

Update object model with data MVC .Net Cannot apply indexing with [] to an expression of type object

[HttpPost]
public string Update(string name, string value) {
    var property = new Models.Property {
        Prop = _db.PROPERTies.SingleOrDefault(p => p.id == 3)
    };

    property[name] = value;
    return name + " " + value;
}

I've trying to get to the "Prop" model inside the property object by passing in the key and value that I'm wanting to change.

name = "Prop.Title"
value = "Test 123

I'm getting the following error

Error   452 Cannot apply indexing with [] to an expression of type 'Namespace.Models.Property'

Is there an alternative way to burrow into the "property" object?

Models.Property

namespace Namespace.Models
{
    public class Property
    {
        public PROPERTy Prop { get; set; }
    }
}

PROPERTy

[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.PROPERTIES")]
public partial class PROPERTy : INotifyPropertyChanging, INotifyPropertyChanged
{
    private string _Title;
}

[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_Title", DbType="VarChar(100)")]
public string Title
{
    get
    {
        return this._Title;
    }
    set
    {
        if ((this._Title != value))
        {
            this.OnTitleChanging(value);
            this.SendPropertyChanging();
            this._Title = value;
            this.SendPropertyChanged("Title");
            this.OnTitleChanged();
        }
    }
}

UPDATE

In order to get it working I followed given advise and indexed the model.

object o = property;
object propValue = o.GetType().GetProperty(name.Split('.')[0]).GetValue(o, null);
propValue.GetType().GetProperty(name.Split('.')[1]).SetValue(propValue, Server.HtmlDecode(value), null);

Upvotes: 0

Views: 309

Answers (1)

Tieson T.
Tieson T.

Reputation: 21191

What you're trying to use is an indexer, but your class doesn't implement that "pattern".

The pattern is relatively simple to implement. At a minimum, add this:

public object this[string key]
{
    get
    {
        var pi = this.GetType().GetProperty(key); // find the property that matches the key
        return pi.GetValue(this, null);
    }
    set
    {
        var pi = this.GetType().GetProperty(key); // find the property that matches the key
        pi.SetValue(this, value, null);
    }
}

It's up to you to make sure that the class actually contains a property matching the key.

Upvotes: 1

Related Questions