I am trying to send a post request to a webapi application hosted in IIS. I get error 500 always with a post request but get request works fine. Below is my code
Model:
public class LineModel
{
[Key]
public string ID { get; set; }
public string No { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Code1 { get; set; }
public string Code2 { get; set; }
public DateTime Date { get; set; }
public string Type { get; set; }
public string Remarks { get; set; }
public string Status { get; set; }
public List<SubLine> SubLines { get; set; }
}
Ajax code displaying the form:
$(function () {
$(".surveyType").click(function () {
var surveyType = $(this).attr("data-bind");
$.ajax({
url: "/Aella/Create/",
data: { "surveyCode": surveyType },
success: function (data) {
console.log(data);
$('#Question').html(data);
};
}
});
});
Ajax call to post request:
$('body').on('click','#submit-request', function () {
var formData = $("#create-request").serialize();
console.log(formData);
$.ajax({
url: "/Aella/Create/",
data: formData,
type: "POST",
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function (data)
{
console.log(data);
}
});
});
Get request:
[HttpGet]
public ActionResult Create(string surveyCode)
{
questions = GetSurveyQuestions(surveyCode);
LineModel model = new LineModel
{
SubLines = questions.Select(a => new SubLine()
{
Question = a.questionField,
Code = a.codeField,
Type = a.question_TypeField.ToString(),
Survey_Type = a.survey_TypeField,
Response = "",
Remark = ""
}).ToList(),
Type = surveyCode,
Date = DateTime.Now
};
return View(model);
}
Post method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(LineModel lineModel)
{
if(ModelState.IsValid)
{
lineModel.Status = "Open";
foreach(var item in lineModel.SubLines)
{
if(item.Type == "Remark")
{
item.Remark = item.Response;
item.Response = "";
}
}
HttpClient client = new HttpClient
{
BaseAddress = new Uri(ConfigurationManager.AppSettings["lineModelLink"].ToString())
};
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
jsonContent = JsonConvert.SerializeObject(lineModel);
contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json");
contentString.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsync(ConfigurationManager.AppSettings["lineModelLink"].ToString(), contentString);
}
catch(HttpRequestException ex)
{
ErrorController.LogError(ex);
ViewBag.Response = JsonConvert.DeserializeObject(responseStr);
if (lineModel.lineModelLines.Count > 0)
{
ViewBag.IsQuestionAvailable = true;
}
return View(lineModel);
}
[...]
}
[...]
}
Postman request:
{
"No":"",
"Name":"",
"Title":"",
"Code1":"",
"Code2":"",
"Date":"2021-10-25T00:00:00",
"Type":"SEC",
"Remarks":"",
"Status":"Open",
"SubLines":
[
{
"Code":"01",
"Question":"How did you learn about the job opening? ",
"Type":"Defined",
"Survey_Type":"SEC",
"Response":"05",
"Remark":""
},
{
"Code":"02",
"Question":"The job description/requirements were clear and understandable",
"Type":"1-4",
"Survey_Type":"SEC",
"Response":"04",
"Remark":""
},
{
"Code":"03",
"Question":"It was easy and convenient applying for the position",
"Type":"1-4",
"Survey_Type":"SEC",
"Response":"04",
"Remark":""
},
{
"Code":"04",
"Question":"The recruiter was professional.",
"Type":"1-4",
"Survey_Type":"SEC",
"Response":"02",
"Remark":""
}
]
}
Form (main view):
@using (Html.BeginForm("Create", "Aella", FormMethod.Post, new { id = "create-request", enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div id="survey-header" class="survey-shape-border">
@Html.EditorFor(model => model.No, new { htmlAttributes = new { @class = "input100" } })
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "input100" } })
@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "input100" } })
@Html.EditorFor(model => model.Code1, new { htmlAttributes = new { @class = "input100" } })
@Html.EditorFor(model => model.Code2, new { htmlAttributes = new { @class = "input100" } })
@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "input100", @readonly = "readonly" } })
@Html.EditorFor(model => model.Type, new { htmlAttributes = new { @class = "input100", @readonly = "readonly" } })
@Html.EditorFor(model => model.Remarks, new { htmlAttributes = new { @class = "input100" } })
@Html.EditorFor(model => model.Status, new { htmlAttributes = new { @class = "input100" } })
</div>
@foreach (var line in Model.SubLines)
{
@Html.Partial("_Lines", line)
}
<div class="display-none">
<button type="button" value="Create" class="btn-lg" id="submit-request">Submit Survey</button>
</div>
</div>
}
Partial View:
@using HtmlHelpers.BeginCollectionItem;
<div class="">
@using (Html.BeginCollectionItem("SubLines"))
{
<div>
@Html.HiddenFor(model => model.ID)
@Html.HiddenFor(model => model.Type)
@Html.HiddenFor(model => model.Type)
@Html.HiddenFor(model => model.Question)
@Html.HiddenFor(m => m.Code)
</div>
if (Model.Type == "Defined")
{
<div class="userDefined_6 survey-line-response">
<label> @Html.RadioButtonFor(model => model.Response, "01")<span>Job Board</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "02")<span>Careers Website</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "03")<span>Linkedin</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "04")<span>Friend/Colleague</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "05")<span>Recruiter</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "06")<span>Others(Please State)</span></label>
</div>
}
if (Model.Type == "1-4")
{
<div class="userDefined_4 survey-line-response">
<label> @Html.RadioButtonFor(model => model.Response, "01")<span>Strongly Disagree</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "02")<span>Disagree</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "03")<span>Agree</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "04")<span>Strongly Agree</span></label>
</div>
}
if (Model.Type == "1-5")
{
<div class="userDefined_5 survey-line-response">
<label> @Html.RadioButtonFor(model => model.Response, "01")<span>1</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "02")<span>2</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "03")<span>3</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "04")<span>4</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "05")<span>5</span></label>
</div>
}
if (Model.Type == "1-15")
{
<div class="userDefined_10 survey-line-response">
<label> @Html.RadioButtonFor(model => model.Response, "01")<span>1</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "02")<span>2</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "03")<span>3</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "04")<span>4</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "05") <span> 5 </span></label>
<label> @Html.RadioButtonFor(model => model.Response, "06")<span>6</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "07")<span>7</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "08")<span>8</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "09")<span>9</span></label>
<label> @Html.RadioButtonFor(model => model.Response, "10")<span>10</span></label>
</div>
}
if (Model.Type == "Open")
{
<div class="userDefined_Narration survey-line-response">
@Html.EditorFor(model => model.Response, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Response, "", new { @class = "text-danger" })
</div>
}
}
</div>
Response from server:
HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 03 Nov 2021 12:15:35 GMT
Content-Length: 36
{"Message":"An error has occurred."}
Spent several hours on this. I will really appreciate help as I am short of answers.
CodePudding user response:
your post ajax request has a bag
url: "/Survey/CreateSurvey/",
but your action is Create. You have to ajust the action name.
and it seems that Get action should be in the same controller , but it has a strange url too
url: "/Aella/Create/",
after fixing these bugs try to debug another parts of the application, one step in a time. Since I can see in your partial view alot of the html helpers I never seen before, I am not sure that they generate right mvc html that can be submitted. SO IMHO comment the partial views and try to make working the main view at first. After this you can continue with partial views adding line by line.
CodePudding user response:
Everything about the code is fine, I observed that the certificate on the server has expired hence the error. Thank you all