Istudent Rana

Istudent Rana

  • 1.8k
  • 292
  • 60.5k

string value is saving as null in database

Jan 22 2018 10:34 AM
Data type of column in database table is nvarchar(max) and allow null is checked.
 
This is my code.
 
This is my ajax post request.
$.ajax({
url: "/Home/SaveAnswer",
type: 'POST',
data: {
"ProjectId": "1",
"QuestionId": qId,
"Answer": text + ',' + rate,
},
cache: false,
}).done(function (response) {
console.log(response);

}).fail(function (e) {
console.log(e);
});
});

Code in controller

[HttpPost]
public string SaveAnswer(AnswerVM model)
{
string msg = "";
try
{
using(MyDbContext context = new MyDbContext())
{
Answer ans = null;
if(ModelState.IsValid)
{

ans = context.Answers.FirstOrDefault(a => a.ProjectId == model.ProjectId && a.QuestionId == model.QuestionId);
if(ans != null)
{
ans.Answer1 = model.Answer;
msg = "ans is not null - {" + ans.Answer1 + "}";
}
else
{
ans = new Answer();
ans.Answer1 = model.Answer;
ans.ProjectId = model.ProjectId;
ans.QuestionId = model.QuestionId;
context.Answers.Add(ans);

msg = "ans is null - {" + ans.Answer1 + "}";
}
context.SaveChanges();
}
}

return msg;
}
catch(System.Exception ex)
{
return ex.Message;
}
}
 

Answers (4)