How to make postback when changing selected list in mvc4

I have a dropdown on my page. When choosing a value from the drop-down list, I want the label text to be changed. Here is my code:

@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)
 }

When changing the value in the drop-down list, I want the description to change accordingly.

+5
source share
1 answer

You can start by adding a description to the div and give your drop-down list a unique identifier:

@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>
}

Now all that remains is to subscribe to the onchangejavascript event of this drop-down list and update the corresponding description.

For example, if you use jQuery, this is a pretty trivial task:

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

, , , , . AJAX , . , , URL- data-* 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);
}
+11

All Articles