How to postback to a controller function when a value is selected from dropdown

11,029

Solution 1

Add this to your layout in the head:

<script type="text/javascript">
    $(document).ready(function () {
        $('select:[autopostback=true],input[type=checkbox]:[autopostback=true],input[type=radio]:[autopostback=true]').live('change',function () {
            $(this).closest('form').submit();
        });
    });
</script>

in your view:

@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"), new { autopostback = "true" })
}

The form that your dropdownlist is in will get submitted when you change selection of your dropdownlist. If the result of the action of that form is the same page, it will be reloaded with whatever stuff being updated

Solution 2

You can't do it without javascript help. Just bind on select event and send the form or make an ajax request.

using jQuery:

$('#yourDropDownId').change(function(){
    $('#yourFormId').submit();
});

or if you need ajax call insted of submit use $.post or $.get.

Solution 3

$(document).ready(function() {
   $("#ddl").change(function() {
       var strSelected = "";
       $("#ddl option:selected").each(function() {
           strSelected += $(this)[0].value;
       });
       var url = "/Home/MyAction/" + strSelected;

       $.post(url, function(data) {
           // do something if necessary
       });
   });
});

or

<%=Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"), new { onchange="this.form.submit();" })%>

Solution 4

It's simple. In your javascript you have:

 $(document).ready(function () {
            $('#SelectedId').change(function () {
                var id = $(this).val();
                $.getJSON("/YourController/YourAction", { id: id},
                function (data) {               
                    $("#SomeDivSelector").html(data);
                });
            });

        });

Your controller should look like:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult YourAction(int id)
{
  //do something
  return Json(ControlToString("~/Views/YourController/YourView.cshtml", yourModelWithData), JsonRequestBehavior.AllowGet);
}

And ControlToString is defined:

 private string ControlToString(string controlPath, object model)
        {
            //CshtmlView control = new CshtmlView(controlPath);
            RazorView control = new RazorView(this.ControllerContext, controlPath, null, false, null);

            this.ViewData.Model = model;

            using (System.Web.UI.HtmlTextWriter writer = new System.Web.UI.HtmlTextWriter(new System.IO.StringWriter()))
            {
                control.Render(new ViewContext(this.ControllerContext, control, this.ViewData, this.TempData, writer), writer);

                string value = ((System.IO.StringWriter)writer.InnerWriter).ToString();
                return value;
            }
        }

Regards.

Share:
11,029
alice7
Author by

alice7

Updated on June 05, 2022

Comments

  • alice7
    alice7 almost 2 years

    I have created a dropdownlist on the view and showing a list.

    @Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.List, "ID", "Name"))
    

    I want to refresh the page when the user selects the value from the drop down. I don't know how to map the selection event from dropdown to a controller function without clicking any button.

    On the view load there is a controller function which is populating the view with the list.

    public ActionResult Populate()
    {
      List<string> list = get it from sql server
      ViewModel viewModel = new ViewModel();
      viewModel.list = list;
       return view();
    }
    

    But how do you call a controller function which will take the selected value as an Id and retrieves the data and refreshes the page with the result.