title: Working with dynamic MVC Controls
body: <p>I am trying to develop a view using razor. In this view, i need to add dropdownlist. But the challenge is that there is no specific property for this dropdownlist in my viewmodel. Based on a value(eg:fieldType) from DB in viewmodel, i decide the type of control. Below is the block of code i am using for that.</p>
  
  <pre><code>@if (Model.fieldValues[i].FieldType.Equals("TEXT"))
  {
      @Html.TextBoxFor(m =&gt; m.fieldValues[i].FieldValue);
  }
  else if (Model.fieldValues[i].FieldType.Equals("MULTIVALUED"))
  {
     @Html.DropDownList(Model.fieldValues[i].OptionFieldValueId.ToString(), Model.fieldValues[i].MultiValueItems)
  }
  </code></pre>
  
  <p>I could manage to get the values populated.However, I am not able to get the 'selected value' working for dropdownlist. Also, how do i access this dropdownlist selected value in controller action?</p>
  
  <p>Here are my main viewmodel and submodel.</p>
  
  <pre><code>public class ValuesGridViewModel
      {
          public List&lt;CompanyFieldValueViewModel&gt; fieldValues { get; set; }
  
          public List&lt;int&gt; UniqueBatchIds
          {
              get
              {
                  return HelperMethods.GetUniqueValues&lt;int&gt;(fieldValues.Select(x =&gt; x.BatchId).ToList());
              }
          }
  
          public List&lt;string&gt; HeaderList
          {
  
              get
              {
                  return HelperMethods.GetUniqueValues&lt;string&gt;(fieldValues.Select(x =&gt; x.Heading).ToList());
              }
          }
      }
  
  
  
    public class CompanyFieldValueViewModel
      {
          public List&lt;MultiValues&gt; MultiValueData { get; set; }
          public int OptionFieldValueId { get; set; }
          public string Heading { get; set; }
          public string FieldValue { get; set; }
          public string FieldType { get; set; }
          public int? MultiValueId { get; set; }
          public int BatchId { get; set; }
  
           public int DisplayOrder { get; set; }
          public List&lt;SelectListItem&gt; MultiValueItems
          {
              get
              {
                  var list = MultiValueData.Where(x=&gt;x.MultiValueId == this.MultiValueId).Select(x =&gt; new SelectListItem()
                  {
                      Text = x.ValueName,
                      Value = x.ValueId.ToString()
                  });
                  return list.ToList();
              }
  
          }
  
      }
  </code></pre>
  
  <p>new to this site. So, sorry for any formatting issues. Thanks in advance!</p>