Get the text from Html.DropdownListFor…MVC3

前端 未结 4 740
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 18:57

I have a model:

public class DocumentModel
{
    public int TypeID { get; set; }
    public List DocumentTypes { get; set; }
}
相关标签:
4条回答
  • 2021-02-04 19:34

    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!

    0 讨论(0)
  • 2021-02-04 19:34

    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"))
    
    0 讨论(0)
  • 2021-02-04 19:37

    I stumbled here trying to find the way to get the text value out of a SelectList to display it in a format other than a DropDownList (I'm reusing my Edit ViewModel as it has all the data I required)

    var text = selectList.Where(q => q.Selected == true).First().Text;
    
    0 讨论(0)
  • 2021-02-04 19:56

    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;
       }
    }
    
    0 讨论(0)
提交回复
热议问题