通过Ajax发布到MVC控制器

时间:2016-02-29 09:40:56

标签: c# jquery ajax visual-studio model-view-controller

您好,我目前正在尝试使用AJAX发布一个控制器,但到目前为止我还没有运气,我一直试图让表单将表单中的值提交给控制器提交表格,但它没有工作,有人知道为什么? :

CSHTML:

@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Abintegro Search Prototype</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
        $("#submitsearch").click(function (e) {
            e.preventDefault();
            var form = $("#searchform");
            $.ajax({
                url: "Search/GetSearchDetails",
                data: form.serialize(),
                type: 'POST',
                success: function (data) {
                    //Show popup
                    $("#popup").html(data);
                }
            });
        });
</script>

    <!-- Javascript function to add autocomplete search phrases for the company name text search-->
    <script>
        $(function () {
            var searchPhrases = [
                "Zep Solutions",
                "Wetherby Consultants Ltd",
                "Webmploy",
                "WATS Recruitment Ltd",
                "Vital Resources",
                "VG Charles and Co",
                "Veredus UK",
                "Venn Group",
                "VanDuo Consulting"
            ];
            $("#phrases").autocomplete({ source: searchPhrases });
        });
</script>
</head>

<body>
    <form id="searchform" name="searchform">

        <div class="company-textbox">
        <label for="companyname">Company Name</label>
        <input id="phrases" name="companyname">
        </div>

        <br />

        <div class="specialities">
            <label for="specialities-dropdown">Specialities:</label>
            <select name="specialities-dropdown">
                <option value="Consumer Products & Services">Consumer Product & Services</option>
                <option value="Support Services">Support Services</option>
                <option value="Communication & Entertainment">Communication & Entertainment</option>
                <option value="Business & Professional Services">Business & Professional Services</option>
                <option value="Public Sector">Public Sector</option>
                <option value="Not for profit">Not for profit</option>
                <option value="Sports Information">Sports Information</option>
            </select>
        </div>

        <br />

        <div class="category">
            <label for="category-dropdown">Category:</label>
            <select name="category-dropdown">
                <option value="Generalist">Generalist</option>
                <option value="Specialist">Specialist</option>
                <option value="Exec Search">Exec Search</option>
                <option value="Interim Management">Interim Management</option>
            </select>
        </div>    

        <br />

        <div class="location-dropdown">
            <label for="location-dropdown">Location:</label>
            <select name="Location">
                <option value="London">London</option>
                <option value="Bristol">Bristol</option>
                <option value="Manchester">Manchester</option>
                <option value="Birmingham">Birmingham</option>
            </select>
        </div>

        <input type="submit" value="Submit" name="submitsearch" id="submitsearch">
    </form>
</body>
</html>

控制器:

 [HttpPost]
        public string GetSearchDetails(string companyName, string specialities, string category, string location)
        {
           return liveSearchRepository.GetUserInputResults(companyName,specialities,category,location);
        }

3 个答案:

答案 0 :(得分:2)

从我看到的内容看起来你的表单控件和你的Controller操作没有正确链接,因为你的控件名称与你的动作参数不同。

还要将ajax调用中的contentType更改为JSON,并将表单数据转换为JSON字符串。这样,如果您在通过Ajax提交表单数据之前将其输出到控制台,您可以看到发送的内容。

尝试以下修改:

@{
    Layout = null;
}
<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Abintegro Search Prototype</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="//code.jquery.com/jquery-1.10.2.js"></script>
    <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
    <script>
        $("#submitsearch").click(function (e) {
            e.preventDefault();

            var formData = JSON.stringify($("#searchform").serializeArray());

            console.log(formData);

            $.ajax({
                url: "Search/GetSearchDetails",
                data: formData,
                type: 'POST',
                contentType: 'json'
                success: function (data) {
                    //Show popup
                    $("#popup").html(data);
                }
            });
        });
</script>

    <!-- Javascript function to add autocomplete search phrases for the company name text search-->
    <script>
        $(function () {
            var searchPhrases = [
                "Zep Solutions",
                "Wetherby Consultants Ltd",
                "Webmploy",
                "WATS Recruitment Ltd",
                "Vital Resources",
                "VG Charles and Co",
                "Veredus UK",
                "Venn Group",
                "VanDuo Consulting"
            ];
            $("#phrases").autocomplete({ source: searchPhrases });
        });
</script>
</head>

<body>
    <form id="searchform" name="searchform">

        <div class="company-textbox">
        <label for="companyName">Company Name</label>
        <input id="phrases" name="companyName">
        </div>

        <br />

        <div class="specialities">
            <label for="specialities">Specialities:</label>
            <select name="specialities">
                <option value="Consumer Products & Services">Consumer Product & Services</option>
                <option value="Support Services">Support Services</option>
                <option value="Communication & Entertainment">Communication & Entertainment</option>
                <option value="Business & Professional Services">Business & Professional Services</option>
                <option value="Public Sector">Public Sector</option>
                <option value="Not for profit">Not for profit</option>
                <option value="Sports Information">Sports Information</option>
            </select>
        </div>

        <br />

        <div class="category">
            <label for="category">Category:</label>
            <select name="category">
                <option value="Generalist">Generalist</option>
                <option value="Specialist">Specialist</option>
                <option value="Exec Search">Exec Search</option>
                <option value="Interim Management">Interim Management</option>
            </select>
        </div>    

        <br />

        <div class="location">
            <label for="location">Location:</label>
            <select name="Location">
                <option value="London">London</option>
                <option value="Bristol">Bristol</option>
                <option value="Manchester">Manchester</option>
                <option value="Birmingham">Birmingham</option>
            </select>
        </div>

        <input type="submit" value="Submit" name="submitsearch" id="submitsearch">
    </form>
</body>
</html>

修改

如果您更改以下行:

var formData = JSON.stringify($("#searchform").serializeArray());

使用这段代码:

var formData = "";
$.each($("#searchform"), function(i,v) {
    if (formData.length > 0) formData += ",";
        formData += v.name + ": '" + v.value + "'";
});
formData = "{ " + formData + " }";

该解决方案将是通用的,如果您更改表单字段的名称,则无需更改代码。

答案 1 :(得分:1)

使用此 Javascript 代码而不是当前代码。我已更正发布数据中的问题,正确的格式如下:

<script>
        $("#submitsearch").click(function (e) {
            var postData = $(this).serializeArray();
            e.preventDefault();
            var form = $("#searchform");
            $.ajax({
                url: "Search/GetSearchDetails",
                data: postData,
                type: 'POST',
                success: function (data) {
                    //Show popup
                    $("#popup").html(data);
                }
            });
        });
</script>

答案 2 :(得分:0)

要修复此问题,以便帖子将值映射到我执行以下操作的参数:

function postToAjax() {
            debugger;
            var companyname = $('#phrases').val().toString();
            var specialities = $('#specialities').val().toString();
            var categorys = $('#categorys').val().toString();
            var locations = $('#locations').val().toString();
            var postData = $(this).serializeArray();
            var form = $("#searchform");
            $.ajax({
                url: "Search/GetSearchDetails",
                data: { 'companyname': companyname, 'specialities': specialities, 'categorys': categorys, 'locations':locations },
                type: 'POST',
                success: function (data) {
                    //Show popup
                    $("#popup").html(data);
                }
            });
        }
   </script>

通过为每个值创建变量,我可以映射数据中的值对,控制器中参数的名称是该对的第一部分,后跟从创建的变量中获取的值,存储来自的值形式元素。