如何在mvc4中更改dropdownlist所选项目时进行回发



我的页面中有一个下拉列表。在下拉列表中选择一个值时,我希望更改标签文本。这是我的代码:

@model FND.Models.ViewLender
@{
    ViewBag.Title = "Change Lender";
 }
@using (Html.BeginForm())
{
    @Html.Label("Change Lender : ")
    @Html.DropDownList("Ddl_Lender", Model.ShowLenderTypes)
    @Html.DisplayFor(model => model.Description)
 }

在更改下拉列表中的值时,我希望"描述"相应地更改。

您可以首先将描述放入div中,并为下拉列表提供一个唯一的id:

@model FND.Models.ViewLender
@{
    ViewBag.Title = "Change Lender";
}
@using (Html.BeginForm())
{
    @Html.Label("Change Lender : ")
    @Html.DropDownList("Ddl_Lender", Model.ShowLenderTypes, new { id = "lenderType" })
    <div id="description">
        @Html.DisplayFor(model => model.Description)
    </div>
}

现在剩下的就是订阅这个下拉列表的onchange javascript事件并更新相应的描述。

例如,如果您正在使用jQuery,那么这是一项非常琐碎的任务:

$(function() {
    $('#lenderType').change(function() {
        var selectedDescription = $(this).find('option:selected').text();
        $('#description').html(selectedDescription);
    });
});

话虽如此,我可能误解了你的问题,这个描述一定来自服务器。在这种情况下,您可以使用AJAX来查询将返回相应描述的控制器操作。我们所需要做的就是将此操作的url作为HTML5数据-*属性提供给下拉列表,以避免在我们的javascript文件中对其进行硬编码:

@Html.DropDownList(
    "Ddl_Lender", 
    Model.ShowLenderTypes, 
    new { 
        id = "lenderType", 
        data_url = Url.Action("GetDescription", "SomeController") 
    }
)

现在在.change事件中,我们触发AJAX请求:

$(function() {
    $('#lenderType').change(function() {
        var selectedValue = $(this).val();
        $.ajax({
            url: $(this).data('url'),
            type: 'GET',
            cache: false,
            data: { value: selectedValue },
            success: function(result) {
                $('#description').html(result.description);
            }
        });
    });
});

当然,最后一步是让这个控制器动作,它将基于所选值获取相应的描述:

public ActionResult GetDescription(string value)
{
    // The value variable that will be passed here will represent
    // the selected value of the dropdown list. So we must go ahead 
    // and retrieve the corresponding description here from wherever
    // this information is stored (a database or something)
    string description = GoGetTheDescription(value);
    return Json(new { description = description }, JsonRequestBehavior.AllowGet);
}

最新更新