显示字符串文本而不是项目ID

时间:2012-04-23 18:42:55

标签: c# asp.net-mvc drop-down-menu

我想从下拉列表中显示以前选择的项目。到目前为止,我只得到显示从之前下拉列表中选择的项目的ID。我想获取项目的文本/描述名称而不是其ID号。

这就是我对viewModel所拥有的:

[LocalizedDisplayName("BillingRate", NameResourceType = typeof(User))]
    public short BillingRateId { get; set; }

    [UIHint("DropDownList")]
    [DropDownList(DropDownListTargetProperty = "BillingRateId")]
    public IEnumerable<SelectListItem> BillingRates { get; set; }

这就是我对.ascx表格页面所拥有的:

<%:Html.LabelFor(m => m.BillingRateId)%>
<%:Html.EditorFor(m => m.BillingRateId, Model.BillingRates)%>
<%:Html.ValidationMessageFor(m => m.BillingRateId)%>

当我运行并查看页面时,我会进入描述框:4 什么时候应该是:实习

2 个答案:

答案 0 :(得分:1)

您可以创建一个只返回该字符串的简单服务,然后使用jQuery AJAX填充它。

public ContentResult GetBillingRate(int id)
{
    //get your billing rate
    return this.Content(billing_rate_string, "text/plain");
}

然后在你的javascript中:

$('#BillingRateId').change(function() {
    $.get('@Url.Action("GetBillinRate", "YourController")/' + $(this).val(),
        function(data) { $('#element_you_want_it_to_show_in').html(data); }
    );
});

答案 1 :(得分:0)

另一种方法是创建自己的IEnumerable并将其推送到DropDownList中。

在您的控制器中:

// this is assuming you can get objects with both name/id for your billing rates 
ViewBag.BillingRates = Db.GetBillingRatesAndNames()
    .Select(x => new SelectListItem() { Text = x.Name, Value = x.Id.ToString() });

在视图中:

<%:Html.EditorFor(m => m.BillingRateId, 
    (IEnumerable<SelectListItem>)ViewBag.BillingItems)%>