1

I have a Razor view in my asp.net MVC3 application with a dropdownlist like this:

@Html.DropDownListFor(model => model.Account.AccountType, new SelectList(Model.AccountTypes, "AccountTypeCode", "Abbreviation"))

This dropdown is inside a form. When form is posted to action method and viewmodel is filled because of model binding, It get the value(AccountTypeCode) and not the text "Abbreviation" property of dropdownlist. I want to get both of these. how can I get these in post action method.

Please suggest.

DotnetSparrow
  • 27,428
  • 62
  • 183
  • 316
  • what do you mean by both of these? You provide display name and value sources to a select list. What do you expect to get when you POST the form ? something else than input's name and it's value ? – Paweł Staniec Feb 13 '12 at 17:09
  • @torm: I want to get selectedItem's value and text in Post action method. currently I am getting Value of selected item only. – DotnetSparrow Feb 13 '12 at 17:32

2 Answers2

0

If you need more than one property of an object as a value for a dropdown, the easiest way is to create a combination of these in a partial class EF 4, how to add partial classes this quesion should help you. You will be able to combine values under one property that you will provide to your dropdown helper.

If you don't want to use partial classes I would advise creating your own helper, that will be a lot easier than trying to use something that does not fit your needs. You can do something like :

    @helper CustomDropdown(string name, IEnumerable<AccountTypes> valueList)
        {
        <select>
            @foreach (var item in valueList)
            {
                <option value="@item.Abbreviation @AccountTypeCode">@item.Abbreviation</option>
            }
        </select>
    }

Google "Creating an Inline HTML Helper" to get some valuable resources on that topic

Community
  • 1
  • 1
Paweł Staniec
  • 3,151
  • 3
  • 29
  • 41
  • Thanks for your quick response. Can I do it without creating partial classes. As I have 5 dropdownlists. I want to get their selected value and selected text in Post action method. – DotnetSparrow Feb 13 '12 at 17:47
0

I struggled with this recently, and the best I could do was:

ViewBag.Message = myModel.myProperty.ToString().

in the controller action. Assuming myProperty is AccountType.

Then in my view I just did

@ViewBag.Message

The next problem I encountered is that it spit out the exact text, without spacing. I had to use a helper to add spacing (but it was based on each word being capitalized, so "ThisIsSomeText" would show up as "This Is Some Text".

REMESQ
  • 1,190
  • 2
  • 26
  • 60