How do I call a post actionresponse passing the se

2019-09-06 16:52发布

问题:

How do I call a post actionresponse passing the selected dropdown item as a parameter from javascript within a view within asp.net, razor, mvc

Basically, as I'm sure you can tell from the below code, I'm trying to accomplish the above without much success. What should I change to be successful? Thanks

<script type="text/javascript">
$(function() {
    $("#mydropdown").change(function() {
        var selectedItem = $(this).val();
        $.ajax({
            url: '@Url.Action("DoStuff", "MainController")',
            type: "Post",
            data: { name: selectedItem },
            success: function () {
                alert('success');
            }
        });

    });
});

    [HttpPost]
    public ActionResult DoStuff(String Selecteditem)
    {
        CIModel CIModellList = CILHelper.ImportFunc(Selecteditem);
        return View(CIModellList);
    }

As of now, nothing happens whem the dropdown is changed. Although if I remove the ajax function, and replace this with an alert. Then the alert in this case does appear.

At this point, both the actionresult and the controller appear as though they do not exist (red) within the project even though both do and are named as stated.

The c# seems to suggest neither the action or the controller actually exist, giving the errors "cannot resolve action" or "cannot resolve controller"

回答1:

<html>
<head>
    <meta charset="utf-8">

    <link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

</head>
<body>

    <select id="mydropdown">
        <option  value="a">a</option>
        <option  value="b">b</option>
        <option  value="c">c</option>
        <option  value="d">d</option>
    </select>



        <script type="text/javascript">
      $(function() {
          $("#mydropdown").change(function() {
              var selectedItem = $(this).val();
              $.ajax({
                  url: '@Url.Action("DoStuff", "MainController")',
                  type: "Post",
                  data: { name: selectedItem },
                  success: function () {
                      alert('success');
                  }
              });

          });
      });
    </script>

</body>
</html>






    [HttpPost]
    public ActionResult DoStuff(string name)
    {
    CIModel CIModellList = CILHelper.ImportFunc(name);
    return View(CIModellList);
    }


回答2:

You must change your name of the parameter to SelectedItem that matches the parameter your action method and stringify your json data before passing like,

JSON.stringify({ SelectedItem :selectedItem })

See this for reference.