//Please I'm trying to post some values from dynamically generated textboxes(like 6 of them). So, I formed an array of subjectIds and questionNumbers with questionNumbers as the content of the textboxes and subjectIds as their Id. I already formed the javascript arrays, wrote a web service to accept the ajax request sincethe same method is not responding from my code behind. When I ran it , its always bringing "System.NullReferenceException: Object reference not set to an instance of an object.
↵ at System.Web.Services.Protocols.ValueCollectionParameterReader.Read(NameValueCollection collection)
↵ at System.Web.Services.Protocols.HtmlFormParameterReader.Read(HttpRequest request)
↵ at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
↵ at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
↵" when I logged it to the console as seen in the below code section. I don't know what I'm doing wrong or maybe my webservice method was not written correctly.
<script type="text/javascript">
$(document).ready(function () {
var messageLabel = $('#lblResult');
// messageLabel.hide();
$('#btnSaveQuestionNoSetting').click(function () {
//var tlength = $("input:text").length;
var subjIds = new Array();
var qNums = new Array();
var i = 0;
$(".inline :input").each(function () {
var count = $(this).attr('name');
subjIds[i] = count;
qNums[i] = $(this).val();
i++;
});
console.log(JSON.stringify(subjIds));
console.log(JSON.stringify(qNums));
$.ajax({
url: "../SettingService.asmx/SaveQuestionSetting",
type: 'POST',
data: { subjectIds: JSON.stringify(subjIds), qCount: JSON.stringify(qNums) },
//async: true,
contentType:"application/x-www-form-urlencoded;charset=UTF-8",
success: function (response) {
console.log(response);
messageLabel.text("Saved successfully");
var btn = $('#btnSaveQuestionNoSetting');
btn.removeClass("btn-blue");
btn.addClass("btn-success");
btn.val("Saved");
messageLabel.fadeOut(5000);
btn.removeClass("btn-success");
btn.addClass("btn-blue");
},
error: function (errMsg) {
console.log("An error has occured");
console.log(errMsg);
}
});
});
});
</script>
//The WebService Method
CBTDLCFDBEntities context = new CBTDLCFDBEntities();
[WebMethod]
public bool SaveQuestionSetting(string[] subjIds, string[] qCounts)
{
bool allValid = false;
int i = 0;
foreach (string id in subjIds)
{
int Id = Convert.ToInt32(id);
int qNumber = Convert.ToInt32(qCounts[i]);
var subjItem = context.Subjects.Where(x => x.SubjectId == Id).FirstOrDefault();
if (subjIds != null)
{
subjItem.NoQuestionToLoad = qNumber;
context.SaveChanges();
allValid = true;
}
i++;
}
return allValid;
}