GetTextfromHtml.DropdownListFor...MVC3我有一个模型:放;}publicListDocumentTypes{get;放;我有一个观点:@Html.DropDownListFor(x=>x.TypeID,Model.DocumentTypes,"-pleaseselect-")我填充我的下拉列表varmodel=newDocumentModel();model.DocumentTypes=GetDocumentTypes();privatestaticListGetDocumentTypes(){varitems=newList{newSelectListItem{Text=@"Text#1",Value="1"},newSelectListItem{Text=@"Text#2",Value="2"},};退换货品;}当表单回发时,我有一个控制器操作:[HttpPost]publicvoidUploadDocument(DocumentModelmodel){if(ModelState.IsValid){//我想从下拉列表中获取文本}}我如何获取我的下拉列表中的文本?谢谢使用默认模型绑定可能不容易使用此功能。你需要这么小的解决方法。1)向模型/视图模型添加新属性以存储选定的文本publicclassDocumentModel{publicintTypeID{get;放;}publicListDocumentTypes{get;放;}publicstringSelctedType{设置;得到;}}2)使用Html.HiddenForHelper方法在表单中为该属性创建一个隐藏变量@Html.HiddenFor(x=>x.SelctedType)3)使用一个小的javascript来覆盖提交!IE;当用户提交表单时,从下拉列表中获取选定的文本并将该值设置为隐藏字段的值。$(function(){$("form").submit(function(){varselTypeText=$("#TypeIDoption:selected").text();$("#SelctedType").val(selTypeText);});});现在,在您的HTTPPost操作方法中,这将在SelectedType属性中可用。[HttpPost]publicvoidUploadDocument(DocumentModelmodel){if(ModelState.IsValid){stringthatValue=model.SelectedType;如果您只想检索所选项目,那么这可以完成这项工作:varselecteItem=model.DocumentTypes.Where(item=>item.Selected).FirstOrDefault();干杯!在你的模型上我会有另一个字符串-publicstringSelected{get;放;然后在你看来:@Html。DropDownListFor(model=>model.Selected,newSelectList(Model.DocumentTypes,"Value","Text"))我偶然发现了这个,试图找到一种方法从SelectList中获取文本值以其他格式显示它比DropDownList(我正在重用我的EditViewModel,因为它有我需要的所有数据)上面是C#教程:从Html.DropdownListFor...MVC3获取文本共享的完整内容,如果它对大家需要了解更多C#教程,希望大家多多关注——vartext=selectList.Where(q=>q.Selected==true).First().Text;本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
