[英]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 谢谢
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 1)向模型/ viewmodel添加新属性以存储选定的文本
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 2)使用Html.HiddenFor
Helper方法在该属性的表单中创建隐藏变量
@Html.HiddenFor(x => x.SelctedType)
3) Use little javascript to override the submit ! 3)使用小javascript覆盖提交! 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
操作方法中,这将在SelectedType
属性中可用。
[HttpPost]
public void UploadDocument(DocumentModel model)
{
if(ModelState.IsValid)
{
string thatValue=model.SelectedType;
}
}
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! 干杯!
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"))
我偶然发现试图找到从SelectList中获取文本值的方法,以DropDownList以外的格式显示它(我正在重用我的Edit ViewModel,因为它具有我需要的所有数据)
var text = selectList.Where(q => q.Selected == true).First().Text;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.