Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the text from Html.DropdownListFor....MVC3

I have a model:

public class DocumentModel
{
    public int TypeID { get; set; }
    public List<SelectListItem> DocumentTypes { get; set; }
}

I have a view:

  @Html.DropDownListFor(x => x.TypeID, Model.DocumentTypes, "- please select -")

I populate my drop down

        var model = new DocumentModel();
        model.DocumentTypes = GetDocumentTypes(); 

private static List<SelectListItem> GetDocumentTypes()
    {

        var items = new List<SelectListItem>
                        {
                            new SelectListItem
                                {Text = @"Text #1", Value = "1"},
                            new SelectListItem
                                {Text = @"Text #2", Value = "2"},
                        };

        return items;

    }

I have a controller action when the form is posted back:

 [HttpPost] 
    public void UploadDocument(DocumentModel model)
    {
        if (ModelState.IsValid)
        {
            // I want to get the text from the dropdown
        }
    }

How do i get the text from my drop down list? Thanks

like image 354
BoundForGlory Avatar asked Jun 14 '12 14:06

BoundForGlory


3 Answers

You may not get this easily with the default model binding. You have to a small workaround like this.

1) Add a new property to your model/viewmodel to store the selected text

public class DocumentModel
{
    public int TypeID { get; set; }
    public List<SelectListItem> DocumentTypes { get; set; }
    public string SelctedType { set;get;}
}

2) Use Html.HiddenFor Helper method to create a hidden variable in the form for this property

@Html.HiddenFor(x => x.SelctedType)

3) Use little javascript to override the submit ! ie; When user submits the form, Get the selected Text from the dropdown and set that value as the value of the Hidden field.

$(function () {
    $("form").submit(function(){
        var selTypeText= $("#TypeID option:selected").text();
        $("#SelctedType").val(selTypeText);           
    });
});

Now in your HTTPPost action method, This will be available in the SelectedType property.

[HttpPost]
public void UploadDocument(DocumentModel model)
{
   if(ModelState.IsValid)
   {
      string thatValue=model.SelectedType;
   }
}
like image 190
Shyju Avatar answered Oct 19 '22 21:10

Shyju


if what you want to do is to retrieve selected item then this can do the work :

  var selecteItem = model.DocumentTypes.Where(item=>item.Selected).FirstOrDefault();

Cheers!

like image 41
Behnam Esmaili Avatar answered Oct 19 '22 23:10

Behnam Esmaili


On your model I would have another string -

public string Selected{ get; set; }

then in your view :

@Html.DropDownListFor(model => model.Selected, new SelectList(Model.DocumentTypes, "Value", "Text"))
like image 27
Ctrl_Alt_Defeat Avatar answered Oct 19 '22 23:10

Ctrl_Alt_Defeat