将基于字符串asp.net mvc的值自动选择DropdownList [英] DropdownListfor to be auto selected on the basis of a value of string asp.net mvc

查看:79
本文介绍了将基于字符串asp.net mvc的值自动选择DropdownList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型中有一个字符串和一个列表属性

I have one string and one list proeprty in my model

public string  _drinkType { get; set; }
public List<SelectListItem> _drinkTypeDropDown { get; set; }

在我看来

@Html.DropDownListFor(m => m._drinkTypeDropDown , new List<SelectListItem>
{
    new SelectListItem{Text="Milk", Value="1"},
    new SelectListItem{Text="coffee", Value="2"},
    new SelectListItem{Text="tea", Value="3"}
}

现在在我的控制器中,我在属性_drinkType中获得值牛奶",茶"和咖啡".当它与属性值

Now in my controller , I am getting the the value "Milk" , "tea" and "coffee" in the property _drinkType. I have to set the selected option in DropdownlistFor when it matches with the property value

有点像 if _drinktype = milk 然后dropdownlistFor将在选择Milk的情况下自动加载

somewhat like if _drinktype = milk then dropdownlistFor will be loaded automatically with Milk selected

推荐答案

您可以在控制器中设置带有可能选项的ViewBag属性,并且模型只能保留将保留实际值的属性.在您的控制器中,将该值添加到ViewBag:

You can set a ViewBag property with the possible options in the controller and the model can keep only the property which will hold the actual value. In your controller, add the value to ViewBag:

ViewBag.DrinkTypeDropDown = new List<SelectListItem>()
{
    new SelectListItem{Text="Milk", Value="1"},
    new SelectListItem{Text="coffee", Value="2"},
    new SelectListItem{Text="tea", Value="3"}
};

在您的列表中,声明下拉列表:

In your, declare the drop down list:

@Html.DropDownListFor(model => model._drinkType, (IEnumerable<SelectListItem>)ViewBag.DrinkTypeDropDown)

编辑:由于具有Text属性,并且如果SelectedListItemValue中存在匹配项,则将选中所选的选项,因此可以在模型中添加属性:

Edit: Since you have the Text property and the selected option will be selected if there is a match in the Value of SelectedListItem, you could add a property in your model:

public string _drinkTypeValue { get; set; }

在从控制器操作结果返回视图之前,您必须基于_drinkType的值设置_drinkTypeValue:

Before returning the view from the controller action result, you would have to set the _drinkTypeValue based on the value of _drinkType:

model._drinkTypeValue = model._drinkTypeDropDown.Where(item => item.Text == model._drinkType).FirstOrDefault().Value; // You will have to treat null values of FirstOrDefault() here

在您看来,将下拉值绑定到_drinkTypeValue:

In your view, bind the drop down value to the _drinkTypeValue:

@Html.DropDownListFor(model => model._drinkTypeValue, Model._drinkTypeDropDown)

当用户提交表单时,它实际上将提交_drinkTypeValue,因此您将不得不以类似的方式将其再次转换为_drinkType.

When the user submits the form, it will actually submit the _drinkTypeValue so you will have to convert it again to _drinkType in a similar fashion.

这篇关于将基于字符串asp.net mvc的值自动选择DropdownList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆