0

I have a select list, I am getting the selected value in action but I want to retrieve the name of select list...

Eg:

<select name="author">
    <option> abc </option> 
    <option> def </option> 
</select>.

I want to get "author" in action.

helion3
  • 34,737
  • 15
  • 57
  • 100

3 Answers3

0
<select name="author"><option selected="selected"> abc </option> <option> def </option> </select>
Maulik patel
  • 2,546
  • 2
  • 20
  • 26
0

Here goes my solution -

Write a simple Extension method which uses Expression to get the Property Name -

public static class ReflectionExtensions
{
    public static string GetPropertyName<T>(Expression<Func<T>> propertyExpression)
    {
        return (propertyExpression.Body as MemberExpression).Member.Name;
    }
}

Then in the view, you can simply use a hiddenfield to hold the name of the property and can retrieve it on the server from hiddenfield -

@Html.Hidden("Hidden1", MVC.Controllers.ReflectionExtensions.GetPropertyName(() => Model.Property));

And in the FormCollection you can get the name of the property.

If you do not want to use any name to HiddenField, then you can use propertyname as the hiddenfield name -

@Html.Hidden(MVC.Controllers.ReflectionExtensions.GetPropertyName(() => Model.SelectedNames), 
    MVC.Controllers.ReflectionExtensions.GetPropertyName(() => Model.SelectedNames));

In this case, you can get both name and value of the hiddenfield as propertynames.

Community
  • 1
  • 1
ramiramilu
  • 17,044
  • 6
  • 49
  • 66
0

I believe placeholder label option is your answer: displays the name 'author' on top of the list, visible by default: video demo

if so, the code is:

<select required>
  <option value=""> author</option>
  <option> abc </option>
  <option> def </option>
</select>

Daniel
  • 379
  • 2
  • 6