Thursday, April 14, 2011

Accessing the object/row being edited in Dynamic Data

I'm modifying the "Edit.aspx" default page template used by ASP.NET Dynamic Data and adding some additional controls. I know that I can find the type of object being edited by looking at DetailsDataSource.GetTable().EntityType, but how can I see the actual object itself? Also, can I change the properties of the object and tell the data context to submit those changes?

From stackoverflow
  • Hi,

    Maybe you have found a solution already, however I'd like to share my expresience on this.

    It turned out to be a great pita, but I've managed to obtain the editing row. I had to extract the DetailsDataSource WhereParameters and then create a query in runtime.

    The code below works for tables with a single primary key. If you have compound keys, I guess, it will require modifications:

    Parameter param = null;
    foreach(object item in (DetailsDataSource.WhereParameters[0] as DynamicQueryStringParameter).GetWhereParameters(DetailsDataSource)) {
        param = (Parameter)item;
        break;
    }
    
    IQueryable query = DetailsDataSource.GetTable().GetQuery();
    ParameterExpression lambdaArgument = Expression.Parameter(query.ElementType, "");
    object paramValue = Convert.ChangeType(param.DefaultValue, param.Type);
    Expression compareExpr = Expression.Equal(
        Expression.Property(lambdaArgument, param.Name),
        Expression.Constant(paramValue)
    );
    Expression lambda = Expression.Lambda(compareExpr, lambdaArgument);
    Expression filteredQuery = Expression.Call(typeof(Queryable), "Where", new Type[] { query.ElementType }, query.Expression, lambda);
    var WANTED = query.Provider.CreateQuery(filteredQuery).Cast<object>().FirstOrDefault<object>();
    
  • If it's a DD object you may be able to use FieldTemplateUserControl.FindFieldTemplate(controlId). Then if you need to you can cast it as an ITextControl to manipulate data.

    Otherwise, try using this extension method to find the child control:

        public static T FindControl<T>(this Control startingControl, string id) where T : Control
        {
            T found = startingControl.FindControl(id) as T;
    
            if (found == null)
            {
                found = FindChildControl<T>(startingControl, id);
            }
    
            return found;
        }
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.