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
{ ... }