Get 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 fill in my picture

  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 submitted back:

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

How to get text from a drop-down list? Thanks

+6
source share
4 answers

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

1) Add a new property to the model / view mode to save the selected text

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

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

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

3) Use a little javascript to override sending! i.e; When the user submits the form, pull the selected text from the drop-down list and set this 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; } } 
+17
source

if you want to get the selected item, then this can do the job:

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

Hurrah!

+2
source

On your model I will have another line -

 public string Selected{ get; set; } 

then in your opinion:

 @Html.DropDownListFor(model => model.Selected, new SelectList(Model.DocumentTypes, "Value", "Text")) 
+1
source

I stumbled upon this while trying to find a way to get a text value from a SelectList in order to display it in a format other than DropDownList (I am reusing my Edit ViewModel as it has all the data I need)

 var text = selectList.Where(q => q.Selected == true).First().Text; 
+1
source

Source: https://habr.com/ru/post/918102/


All Articles