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

ram*_*mya 5 asp.net-mvc-4

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

@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)
 }
Run Code Online (Sandbox Code Playgroud)

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

Dar*_*rov 11

您可以首先将描述放入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>
}
Run Code Online (Sandbox Code Playgroud)

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

例如,如果您使用jQuery这是非常简单的任务:

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

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

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

现在.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);
            }
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

当然最后一步是让这个控制器动作根据所选值获取相应的描述:

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);
}
Run Code Online (Sandbox Code Playgroud)