Pass a parameter to a controller using jquery ajax

前端 未结 3 1540
春和景丽
春和景丽 2020-12-01 16:18

I have created a view and a controller, the controller I am wanting to return some search results. I am calling the controller using jquery

   

        
3条回答
  •  我在风中等你
    2020-12-01 17:02

    The problem is in order for the DefaultModelBinder to work it needs to match the parameter by name. You could change the name of your action parameter to the name of the "id" in your default route, which is "id" by default, then do this;

            $("#search").click(function () {
                alert('called');
                var url = '/Ingredients/Search/' + $('#search').val();
                $.ajax({
                    url: url,
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        alert(data);
                    },
                    error: function () {
                        alert("error");
                    }
                });
            });
    

    Or, you could write the Json string yourself to construct it in a way that would be matched at server side;

           $("#search").click(function () {
                alert('called');
                var p = { "input": $('#search').val() };
                $.ajax({
                    url: '/Ingredients/Search',
                    type: "POST",
                    data: p,
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        alert(data);
                    },
                    error: function () {
                        alert("error");
                    }
                });
            });
    

    This is untested but should work.

提交回复
热议问题