简体   繁体   English

通过Ajax发布到MVC控制器

[英]Posting via Ajax to MVC controller

Hi I'm currently trying to get a form to post a controller using AJAX however I've had no luck so far, I have been trying to get the form to submit the values in the form to the controller on the submit of the form but it won't work does anybody know why? 嗨我目前正在尝试使用AJAX发布一个控制器的表单但是到目前为止我没有运气,我一直试图让表单将表单中的值提交给控制器提交表单但是,任何人都知道为什么不行? :

CSHTML: 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>

Controller: 控制器:

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

From what I can see it looks like your form controls and your Controller action does not link up properly because your controls' names is not the same as your action's parameters. 从我可以看到它看起来像您的表单控件和您的Controller操作没有正确链接,因为您的控件的名称与您的操作的参数不同。

Also change the contentType in your ajax call to JSON and convert the form data to a JSON string. 还要将ajax调用中的contentType更改为JSON,并将表单数据转换为JSON字符串。 That way if you output the form data to the console before submitting it via Ajax, you can see what is sent through. 这样,如果您在通过Ajax提交表单数据之前将其输出到控制台,您可以看到发送的内容。

Try the following modifications: 请尝试以下修改:

 @{ 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> 

EDIT 编辑

If you change the following line: 如果更改以下行:

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

With this piece of code: 有了这段代码:

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

The solution will be generic and you would not have to change the code if you change the names of the form field. 该解决方案将是通用的,如果您更改表单字段的名称,则无需更改代码。

Use this Javascript code instead of current one. 使用此Javascript代码而不是当前代码。 I have corrected issues in post data and the correct formate is below : 我已经更正了帖子数据中的问题,正确的格式如下:

 <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> 

To fix this issue so that the post mapped the values to the parameters I did the following: 要解决此问题,以便post将值映射到参数,我执行以下操作:

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>

By creating variables for each value I could then map the value pairs in the data, the name of the parameter in the controller is the first part of the pair, followed by the value taken from the created variables storing the values from the form element. 通过为每个值创建变量,我可以映射数据中的值对,控制器中参数的名称是该对的第一部分,后跟从存储表单元素中的值的创建变量中获取的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM