【发布时间】:2017-03-05 23:26:18
【问题描述】:
这现在需要用户选择下拉值之一。 如果当前值为空,如何将下拉选择的值设置为“Rate1”? (Modal 加载时是这样的)
最后,设置@class= "form-control" 的状态 到: @class= “表单控件已编辑”当模式加载时选择的值?
我在下拉列表中有 4 个费率作为查找填充:
case "BillingRates":
{
strArrays = new string[] { "Rate1", "Rate2", "Rate3", "Rate4" };
for (i = 0; i < (int)strArrays.Length; i++)
{
string str4 = strArrays[i];
lookups.Add(new Lookup()
{
Text = str4,
Value = str4,
TenantId = currentTenantId,
Selected = false,
Disabled = false,
Group = null,
AssociatedClass = string.Empty
});
}
break;
}
我还使用这个 foreach 来查找下拉菜单的 BillingRates:
foreach (Lookup lookupItem in (new LookupFill("BillingRates", num)).LookupItems)
{
SelectListItem selectListItem3 = new SelectListItem()
{
Text = lookupItem.Text,
Value = lookupItem.Value,
Disabled = lookupItem.Disabled,
Selected = lookupItem.Selected
};
selectListItems5.Add(selectListItem3);
}
SelectListItem selectListItem4 = new SelectListItem()
{
Text = "",
Value = "",
Disabled = false
};
然后我在我的 cshtml 文件中有这个变量:
var selectedBillingRate = string.Empty;
var BillingRates = ViewData["BillingRates"] as IEnumerable<SelectListItem>;
foreach (var item in BillingRates)
{
if (item.Value == Model.Invoice.BillingRate) { selectedBillingRate = item.Value; break; }
}
var BillingRateSelect = new SelectList(BillingRates, "Value", "Text");
var selectedBillingRate = '@Html.Raw(selectedBillingRate)';
$('#BillingRate').val(selectedBillingRate);
最后,我将这个作为我的 DropDownList:
@Html.DropDownList("BillingRate", BillingRateSelect, new { id = "BillingRate", required = "required", @class = "form-control" + (!string.IsNullOrEmpty(Model.Invoice.BillingRate) || !string.IsNullOrEmpty(selectedBillingRate) ? " edited" : "") })
【问题讨论】:
-
DropDownList()(以及首选的DropDownListFor())方法绑定到您的属性值。在将模型传递给视图之前,您需要在 GET 方法中设置BillingRate的值(并且在绑定到模型属性时忽略设置SelectListItem的Selected属性) -
@StephenMuecke 谢谢你,但是,你建议我在哪里做最好?我继承了这段代码,但我不确定在 GET 方法中设置
BillingRate的值的位置或确切的方法是什么?再次感谢! -
您没有显示您的模型或 GET 方法,但假设您将其初始化为 -
var model = ...;(填充模型的一些代码),那么您可以执行类似if(model.BillingRate == null) { model.BillingRate = someValue; }; return View(model); -
在页面加载时提供视图和操作会更好(意味着模型为空时)
标签: c# asp.net-mvc