从Html.DropdownListFor .... MVC3获取文本

Bou*_*ory 6 c# asp.net-mvc-3

我有一个模特:

public class DocumentModel
{
    public int TypeID { get; set; }
    public List<SelectListItem> DocumentTypes { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我有一个观点:

  @Html.DropDownListFor(x => x.TypeID, Model.DocumentTypes, "- please select -")
Run Code Online (Sandbox Code Playgroud)

我填充了我的下拉

        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;

    }
Run Code Online (Sandbox Code Playgroud)

回传表单时,我有一个控制器操作:

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

如何从我的下拉列表中获取文本?谢谢

Shy*_*yju 19

使用默认模型绑定可能无法轻松获得此信息.你需要这样一个小的解决方法.

1)向模型/ viewmodel添加新属性以存储选定的文本

public class DocumentModel
{
    public int TypeID { get; set; }
    public List<SelectListItem> DocumentTypes { get; set; }
    public string SelctedType { set;get;}
}
Run Code Online (Sandbox Code Playgroud)

2)使用Html.HiddenForHelper方法在此属性的表单中创建隐藏变量

@Html.HiddenFor(x => x.SelctedType)
Run Code Online (Sandbox Code Playgroud)

3)使用小javascript覆盖提交!即; 当用户提交表单时,从下拉列表中获取所选文本,并将该值设置为隐藏字段的值.

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

现在,在您的HTTPPost操作方法中,这将在SelectedType属性中可用.

[HttpPost]
public void UploadDocument(DocumentModel model)
{
   if(ModelState.IsValid)
   {
      string thatValue=model.SelectedType;
   }
}
Run Code Online (Sandbox Code Playgroud)