horizon1711
horizon1711

Reputation: 152

Getting model property using custom field names

I have a model with properties like this

[Display(Name = "Option Value 1")]
public string option_value1;
[Display(Name = "Option Value 2")]
public string option_value2;
[Display(Name = "Option Value 3")]
public string option_value3;
[Display(Name = "Option Value 4")]
public string option_value4;

...
...
[Display(Name = "Option Value n")]
public string option_valuen;

And I want to do something in views like

for (i = 0;i < n; i++) {
if (Model.getProperty("Option_Value"+i) != null) 
{
then display "Option_Value"+i
}

I can do it very smooth in cakephp, is that possible in ASP.NET MVC too?

Upvotes: 1

Views: 1021

Answers (2)

R&#233;da Mattar
R&#233;da Mattar

Reputation: 4381

Another way to do it, if you can't use an array, is to use weakly typed versions of HtmlHelpers :

@for (i = 0; i < n; i++)
{
     @Html.Display("option_value" + i)
}

You can replace Display with Editor if you want a textbox for edition purpose.

Upvotes: 1

Anders Abel
Anders Abel

Reputation: 69310

Yes, it's possible by using an array. Instead of creating a separate property for each of the options, you should have one property in your model:

public string[] Options { get; set; }

Then you will be able to loop through it and access the options with an index.

When creating inputs for that string, you have to use a for loop with an index to get MVC to generate the right id and name attributes of the inputs:

@for(int i = 0; i < Model.Options.Length)
{
  @Html.EditorFor(m => Model.Options[i])
}

Upvotes: 1

Related Questions