Define model the attribute of type Two-dimensional Array

1

There is a way to create a two-dimensional array attribute in Model so you can use this attribute to mount a table on View .

Example: In model I define an array type array and the controller defines that the array will be 20x20 and each position will have X value, for example, and in view will have a int[,] matriz traversing the array to mount a table with x filled in each cell.

I created attributes with several columns and in controller I use a list of enumerable type with 20 positions, but I did not find it legal because I want the assembly of the array to be more dynamic.

    
asked by anonymous 04.11.2015 / 12:36

1 answer

0
  I created attributes with several columns and in controller I use a list of enumerable type with 20 positions, but I did not find it legal because I want the assembly of array would be more dynamic.

By definition, arrays are not dynamic. If the idea is to be more dynamic, use objects that work well with variable number of indexes, such as List<T> " or Dictionary<TKey, TValue> .

Still, if you want to work with View level arrays you can implement the ModelBinder below:

public class TwoDimensionalArrayBinder<T> : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        string key = bindingContext.ModelName;
        try
        {
            int totalRows = 0;
            while (bindingContext.ValueProvider.GetValue(key + totalRows) != null)
                totalRows++;
            ValueProviderResult[] val = new ValueProviderResult[totalRows];
            for (int i = 0; i < totalRows; i++)
                val[i] = bindingContext.ValueProvider.GetValue(key + i);
            if (val.Length > 0)
            {
                int totalColumn = ((string[])val[0].RawValue).Length;
                T[,] twoDimensionalArray = new T[totalRows, totalColumn];
                StringBuilder attemptedValue = new StringBuilder();
                for (int i = 0; i < totalRows; i++)
                {
                    for (int j = 0; j < totalColumn; j++)
                    {
                        twoDimensionalArray[i, j] = (T)Convert.ChangeType(((string[])val[i].RawValue)[j], typeof(T));
                        attemptedValue.Append(twoDimensionalArray[i, j]);
                    }
                }
                bindingContext.ModelState.SetModelValue(key, new ValueProviderResult(twoDimensionalArray, attemptedValue.ToString(), CultureInfo.InvariantCulture));
                return twoDimensionalArray;
            }
        }
        catch
        {
            bindingContext.ModelState.AddModelError(key, "Data is not in correct Format");
        }
        return null;
    }
}

And use like this:

[HttpPost]
public ActionResult Index([ModelBinder(typeof(TwoDimensionalArrayBinder<int>))] int[,] Matriz
{ ... }
    
29.08.2016 / 16:49