In the Model created attributes with multiple columns and in controller use a list of type enumerable with 20 positions, but did not find it cool because I want the mounting of the array was 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 indices, such as List<T>
or Dictionary<TKey, TValue>
.
Still, if you want to work with matrices at the level of View can implement the Modelbinder down 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 wear it like this:
[HttpPost]
public ActionResult Index([ModelBinder(typeof(TwoDimensionalArrayBinder<int>))] int[,] Matriz
{ ... }
Yes, you can. Enter your code so we can address.
– Fernando Mondo