通过 Ajax 发布到 MVC 控制器

Posted

技术标签:

【中文标题】通过 Ajax 发布到 MVC 控制器【英文标题】:Posting via Ajax to MVC controller 【发布时间】:2016-06-12 07:03:27 【问题描述】:

您好,我目前正在尝试使用 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);
        

【问题讨论】:

form.serialize() 产生了什么?最好为 POST 操作创建一个 poco 类,并从脚本中相应地感知数据。 尝试插入 dataType: "html",作为 .ajax 调用中的参数 究竟是什么不工作?您可以调试 Javascript 以验证它应该将发布数据发送到您的控制器吗? 在调试器中,使用 Chromes 调试器,函数似乎在 $("#submitsearch").click(function (e) 【参考方案1】:

据我所见,您的表单控件和控制器操作似乎没有正确链接,因为您的控件名称与您的操作参数不同。

还将您的 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 + " ";

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

【讨论】:

["name":"companyname","value":"Wetherby Consultants Ltd","name":"specialities","value":"Consumer Products & Services", "name":"categorys","value":"Generalist","name":"locations","value":"London"] [HttpPost] public string GetSearchDetails(string companyname, string specialities, string categories, string locations) return liveSearchRepository.GetUserInputResults(companyname,specialities,categorys,locations); 在上面这是发布的数据我现在点击控制器但每个参数都是空的? 函数 postToAjax() 调试器; var formData = JSON.stringify($("#searchform"));控制台.log(formData); $.ajax( url: "Search/GetSearchDetails", data: formData, contentType: "application/json; charset=utf-8", type: 'POST', success: function (data) //显示弹窗 $( "#popup").html(数据); ); 【参考方案2】:

使用此 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>

【讨论】:

当我调试这段代码时,它会到达: $("#submitsearch").click(function (e) 然后进入一个名为 BrowserLink 的文件,它似乎陷入了一个循环,代码示例: (i.log("Invalid transport: "+f+", 从传输列表中删除它。"),t.splice(u,1));t.length===0&&(i. log("指定的传输数组中没有保留任何传输。"),t=null)else if(n.type(t)==="object"||r.transports[t]||t===" auto")if(t==="auto"&&r._.ieVersion 您能否使用浏览器检查元素工具检查控制台并分享您收到的错误。 这不是错误,它只是卡在一个名为“BrowserLink”的文件中的一行代码的循环中 你能把你有问题的网站的链接发给我吗?【参考方案3】:

为了解决这个问题,以便帖子将值映射到参数,我执行了以下操作:

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>

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

【讨论】:

通过遍历表单中的控件,您可以使其具有通用性,以防止在表单控件更改或您应该添加另一个控件时必须更改代码。请参阅我的答案中的编辑以获取此示例。

以上是关于通过 Ajax 发布到 MVC 控制器的主要内容,如果未能解决你的问题,请参考以下文章

Ajax 将空对象发布到 mvc 控制器

使用 AJAX 将 JavaScript 数组发布到 asp.net MVC 控制器

为啥通过 jQuery Ajax 将 Plaid 链接结果发布到 ASP.NET MVC 控制器时缺少属性数据?

使用 ajax 以 mvc 模式通过控制器发送数据

如何在 ASP.NET MVC 中将 base64String 转换为 blob 并通过 ajax 发送到控制器?

.net core 3.1将ajax对象列表发布到MVC控制器没有数据到达