I have an ASP.NET MVC application which has the following form in the view:
@using (Html.BeginForm("Updated", "OnlineEnrollment", FormMethod.Post))
{
<section id="agreement" style="background-color: #508bfc;">
<div >
<div >
<div >
<div style="border-radius: 1rem;">
<div >
<h3 >Participant Agreement for Online Enrollment</h3>
<div id="agreenmentDIV" >
<div id="AgreementContent" >
<button type="button" id="agreementButton" onclick="return DisplayProgressMessage(this, 'agreement');">I Agree</button>
<button 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" style="background-color: #508bfc;">
<div >
<div >
<div >
<div style="border-radius: 1rem;">
<div >
<h3 >Online Enrollment</h3>
<h5 >Step 3 of 3</h5>
<div id="summaryDIV" >
<div id="summaryContent" >
<div >
<label >
Please review the contribution rate and election selections below.
</label>
</div>
<div >
<label >Contribution Rate</label>
<label 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 type="button" id="submitButton" onclick="return SaveData(this, 'confirm');">Confirm</button>
<button type="button" id="restartButton" onclick="return StartOver(this, 'restart');">Start All Over</button>
<button 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:
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:
[
{ "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:
[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:
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.
And I never hit the breakpoint that I have set in the controller. The breakpoint is set on the declaration of returnString.
Any ideas why this ajax call does not send data to the controller?
Thanks!
Edit 1: This is a picture of the Payload from the network tab:
CodePudding user response:
for the start you have a wrong url, assuming the controller name is OnlineEnrollment your url should be /OnlineEnrollment/SaveElectionData. Dont stringify sendData, and remove 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
[HttpPost("~/OnlineEnrollment/SaveElectionData")]
public string SaveElectionData(List<FundElection> formData)
{
//...
}
or you can use contentType: 'application/json; and stringify data in this case and use FromBody attribute
...
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
[HttpPost("~/OnlineEnrollment/SaveElectionData")]
public string SaveElectionData([FromBody] List<FundElection> formData)
{
//...
}
CodePudding user response:
Try to change $.ajax
to following:
$.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:
[HttpPost]
public string SaveElectionData([FromBody] List<FundElection> formData)
{
//...
}
In addition replace first line in View
component:
@using (Html.BeginForm("Updated", "OnlineEnrollment", FormMethod.Post))
with simple <form>
element. Of course, you should add </form>
in the end of html. ;)