简体   繁体   English

C# ASP.NET MVC 应用程序与 ajax 在视图中从不发送数据到 Z594C103F2C6E010C3D8ABE059

[英]C# ASP.NET MVC application with ajax in view never sends data to controller

I have an ASP.NET MVC application which has the following form in the view:我有一个 ASP.NET MVC 应用程序,它在视图中具有以下形式:

@using (Html.BeginForm("Updated", "OnlineEnrollment", FormMethod.Post))
{

 <section id="agreement" class="vh-100" style="background-color: #508bfc;">
    <div class="container py-5 h-100">

        <div class="row d-flex justify-content-center align-items-center h-100">
            <div class="col-12 col-md-8 col-lg-6 col-xl-5">
                <div class="card shadow-2-strong" style="border-radius: 1rem;">
                    <div class="card-body p-5 text-center scrollHeight">

                        <h3 class="mb-5">Participant Agreement for Online Enrollment</h3>
                        <div id="agreenmentDIV" class="myDIV">
                            <div id="AgreementContent" class="content800">
                                <button class="btn btn-primary btn-lg btn-block" type="button" id="agreementButton" onclick="return DisplayProgressMessage(this, 'agreement');">I Agree</button>
                                <button class="btn btn-outline-primary btn-lg btn-block" type="button" id="cancelAgreementButton" onclick="return Cancel(this, 'agreement');">I DO NOT Agree</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>
<section id="summary" class="vh-100 hideit" style="background-color: #508bfc;">
    <div class="container py-5 h-100">

        <div class="row d-flex justify-content-center align-items-center h-100">
            <div class="col-12 col-md-8 col-lg-6 col-xl-5">
                <div class="card shadow-2-strong" style="border-radius: 1rem;">
                    <div class="card-body p-3 text-center scrollHeight">

                        <h3 class="mb-5">Online Enrollment</h3>

                        <h5 class="mb-5">Step 3 of 3</h5>

                        <div id="summaryDIV" class="myDIV">
                            <div id="summaryContent" class="content800">

                                <div class="form-outline mb-4">
                                    <label class="form-label text-left width95">
                                        Please review the contribution rate and election selections below.
                                    </label>
                                </div>
                                <div class="row width95">
                                    <label class="col-sm-9 col-form-label text-left">Contribution Rate</label>
                                    <label class="col-sm-3 col-form-label text-right" id="summaryRate"> </label>
                                </div>
                                <hr width=”75%” align=”center”>
                                <div id="summaryRow">
                                      <  show a summary of the data to be sent to the controller   >
                                </div>
                                <br />
                                <button class="btn btn-primary btn-lg btn-block" type="button" id="submitButton" onclick="return SaveData(this, 'confirm');">Confirm</button>
                                <button class="btn btn-warning btn-lg btn-block" type="button" id="restartButton" onclick="return StartOver(this, 'restart');">Start All Over</button>
                                <button class="btn btn-outline-primary btn-lg btn-block" type="button" id="cancelSummaryButton" onclick="return Cancel(this, 'cancel');">Cancel</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

In jQuery, I have this code:在 jQuery 中,我有以下代码:

function SaveData(ctl, msg) {
    $(".submit-progress").removeClass("hidden");
    const myTimeout = setTimeout(function () {

        var sendData = [];
        var fundName = "";
        var percent = $("#electedRate").val();
        var fund = 0;
        var data = {};

        //
        // put the contribution rate into the object to send to the controller
        // we use fund = 0 to indicate this is the deferral rate
        //

        data = {
            'fund': fund,
            'fundName': fundName,
            'percent': percent
        };
        sendData.push(data);
        $('.election').each(function () {
            percent = parseInt($(this).val());
            if (percent > 0) {
                fund = $(this).next().val();
                fundName = $(this).parent().prev().text();
                data = {
                    'fund': fund,
                    'fundName': fundName,
                    'percent': percent
                };
                sendData.push(data);
            }
        });
        sendData = JSON.stringify(sendData);
        console.log(sendData);
        $.ajax({
            type: "POST",
            url: "@Url.Action("SaveElectionData")",
            dataType: "text",
            data: { 'formData': sendData },
            success: function (msg) {
                $("#Updated").submit();
            },
            error: function (req, status, error) {
                $("form").submit();
            }
        });
    }, 5);

}

When I run the application, and I look at the console under dev tools, for sendData, I see this:当我运行应用程序并查看开发工具下的控制台时,对于 sendData,我看到:

[
    { "fund": 0, "fundName": "", "percent": "0" },
    { "fund": "66", "fundName": "American Funds 2060 Target Date Fund", "percent": 100 }
]

This is exactly what I anticipated on seeing.这正是我所期望的。

And this is the code in the controller that the ajax should be sending the form data to:这是 controller 中的代码,ajax 应该将表单数据发送到:

    [HttpPost]
    public string SaveElectionData(List<FundElection> formData)
    {
        var returnString = "";
        string rateS = "";

        var MQMessage = participantSessionData.mqKey + "INTERNET/009EM";

        foreach (var record in formData)
        {
            bool res = false;
            int fund = 0;
            int pct = 0;

            res = Int32.TryParse(record.fund, out fund);
            res = Int32.TryParse(record.percent, out pct);

            string fundS = fund.ToString();
            string pctS = pct.ToString();

            if (fund == 0)
            {
                if (pct < 10)
                {
                    rateS = "0" + pct.ToString();
                } 
                else
                {
                    if (pct == 100)
                    {
                        rateS = "99";
                    } 
                    else
                    {
                        rateS = pctS;
                    }
                }
            }
            else
            {
                if (fundS.Length == 1 )
                {
                    fundS = "0" + fundS;
                }

                if (pctS.Length == 1)
                {
                    pctS = "00" + pctS;
                } 
                else
                {
                    if (pctS.Length < 3)
                    {
                        pctS = "0" + pctS;
                    }
                }

                MQMessage = MQMessage + fundS + pctS;
            }
        }

        < code to update database >

        MQMessage = participantSessionData.mqKey + "INTERNET/009RK" + rateS;
        participantSessionData = _mqSendRepo.mq6000Send(MQMessage, participantSessionData);

        < code to update database >

    return returnString;
}

And this is the model for FundElection:这是用于 FundElection 的 model:

public class FundElection
{
    public string percent { get; set; }
    public string fund { get; set; }
    public string fundName { get; set; }
}

I am getting the following error page:我收到以下错误页面:

This site can't be reached.无法访问此站点。

The webpage at https://localhost:44353/OnlineEnrollment/Updated might be temporarily down or it may have moved permanently to a new web address. https://localhost:44353/OnlineEnrollment/Updated 的网页可能暂时关闭,或者它可能已永久移动到新的 web 地址。

And I never hit the breakpoint that I have set in the controller.而且我从来没有碰到我在 controller 中设置的断点。 The breakpoint is set on the declaration of returnString.断点设置在 returnString 的声明上。

Any ideas why this ajax call does not send data to the controller?任何想法为什么这个 ajax 调用不向 controller 发送数据?

Thanks!谢谢!

Edit 1: This is a picture of the Payload from the network tab:编辑 1:这是来自网络选项卡的有效负载图片:

在此处输入图像描述

Try to change $.ajax to following:尝试将$.ajax更改为以下内容:

$.ajax({
  type: "POST",
  url: "@Url.Action("SaveElectionData")",
  contentType: "application/json",
  data: sendData,
  success: function (msg) {
      $("#Updated").submit();
  },
  error: function (req, status, error) {
      $("form").submit();
  }
});

And change method in controller to:并将 controller 中的方法更改为:

[HttpPost]
public string SaveElectionData([FromBody] List<FundElection> formData)
{
    //...
}

And are you sure that you get right url parameter in $.ajax ?你确定你在$.ajax中得到了正确的url参数吗?

for the start you have a wrong url, assuming the controller name is OnlineEnrollment your url should be /OnlineEnrollment/SaveElectionData.首先你有一个错误的 url,假设 controller 名称是 OnlineEnrollment 你的 url 应该是 /OnlineEnrollmentData.SaveEle Dont stringify sendData, and remove dataType不要对 sendData 进行字符串化,并删除 dataType


       // sendData = JSON.stringify(sendData);

        $.ajax({
            type: "POST",
             url:"/OnlineEnrollment/SaveElectionData",

             //dataType: "text",

            data: { formData: sendData},
           ....

if ajax still doesn't hit an action, try to use an attribute route如果 ajax 仍然没有命中动作,请尝试使用属性路由

[HttpPost("~/OnlineEnrollment/SaveElectionData")]
public string SaveElectionData(List<FundElection> formData)
{
    //...
}

or you can use contentType: 'application/json;或者你可以使用 contentType: 'application/json; and stringify data in this case and use FromBody attribute在这种情况下对数据进行字符串化并使用 FromBody 属性

...
 type: 'POST',
 url:'/OnlineEnrollment/SaveElectionData',
 contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  data: JSON.stringify(sendData),
...

if ajax still doesn't hit an action, try to use an attribute route如果 ajax 仍然没有命中动作,请尝试使用属性路由

[HttpPost("~/OnlineEnrollment/SaveElectionData")]
public string SaveElectionData([FromBody] List<FundElection> formData)
{
    //...
}

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

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