Invoking particular action on dropdown list selection in MVC

后端 未结 7 1778
时光取名叫无心
时光取名叫无心 2021-02-01 18:08

I have a dropdown list in an MVC view. On selection change of dropdown list I want to call specific action method in the controller.

What I have done on view is this :

相关标签:
7条回答
  • 2021-02-01 18:47

    Do you really need to submit the form? You could redirect:

    onchange = "redirect(this.value)"
    

    where redirect is a custom defined function:

    function redirect(dropDownValue) {
        window.location.href = '/myController/myAction/' + dropDownValue;
    }
    
    0 讨论(0)
  • 2021-02-01 18:47

    @Shimmy is there a way to do this as a one-liner, without defining the function in js?

    yes you can and here is the code for that:

    @Html.DropDownListFor(m => m.Name, new SelectList((System.Collections.IEnumerable)ViewBag.DropDownName, "Value", "Text"), new { @class = "form-control", onchange = "document.location.href = '/Home/Employee?c=' + this.options[this.selectedIndex].value;" })
    
    0 讨论(0)
  • 2021-02-01 18:49

    This is a jQuery thing. Give it a class and wire up to it.

    Html.DropDownList("ddl", AvailableList, new { @class = "_select_change" })
    

    A rough script might look like this:

    $('._select_change').change(function() { $.post(ctrlUrl); })
    
    0 讨论(0)
  • 2021-02-01 19:00

    Your approach should work. The issue you're encountering is your use of this in your onchange event is invalid. Try replacing your this.form references with something like this:

    <%= Html.DropDownList(
            "ddl", ViewData["AvailableList"] as SelectList, 
            new { onchange = @"
                var form = document.forms[0]; 
                form.action='MyMethod';
                form.submit();" 
            } ) %>
    
    0 讨论(0)
  • 2021-02-01 19:02

    Like both : D

    I propose a mix -I like a lot the jQuery.

    $('ddl').change(
     function() {
      // This contains your selected option val
      $(this).val();
    
    // so you can do domething like...
      $.post(
        $(this).val(),
        { Param1: xxxx,
          Param2: xxxx,
          Param3: xxxx },
        function(data) {
         // handle your call here. 'data' contains the response
        } );
    }
    
    0 讨论(0)
  • 2021-02-01 19:03
    @Html.DropDownListFor(model => model.StudentId, new SelectList(ViewBag.List, "Value", "Text"), new { @class = "form-control", @style = "width:65px", onchange = "document.location.href = '/Student/find?Id=' + this.options[this.selectedIndex].value;" })
    
    0 讨论(0)
提交回复
热议问题