I am trying as the title says to return a Json message from the Controller to the View after it validates.
I have made a breakpoint, and I know that the code works from Controller side, and that my JavaScript calls with success the ActionResult now. How do I display that message in the View?
There are two buttons, stamp in and stamp out. If the user stamps in twice, it should get a message, same with stamp out. I have two ActionResults who are indentical except some message and string changes.
Controller:
[HttpPost]
public ActionResult CreateStamp(Stamping stampingmodel)
{
var validateMsg = ;
stampingmodel.Timestamp = DateTime.Now;
stampingmodel.StampingType = in;
if (stampingmodel.User == null || ModelState.IsValid)
{
var idValidated = db.Users.Find(model.UserId);
if (idValidated != null)
{
var stamp =
db.Stampings.Where(s => s.UserId == stampingmodel.UserId)
.OrderByDescending(s => s.Timestamp)
.FirstOrDefault();
if (stamp.StampingType == stampingmodel.StampingType)
{
if (stampingmodel.StampingType == in)
{
validateMsg = Stamped Twice In A Row!;
}
}
else
{
if (stampingmodel.StampingType == in)
{
validateMsg = Stamped In, Welcome.;
}
}
}
db.Stampings.Add(stampingmodel);
db.SaveChanges();
}
return Json(new {Message = validateMsg });
JavaScript:
$(document).ready(function () {
$(#stampInBtn).click(function () {
var userId = $(#userId).val();
$.ajax({
url: ComeAndGo/CreateStamp,
type: POST,
dataType: json,
data: {
userId: userId,
}
});
});
View:
<input type=text id=idUser class=form-control />
<br />
<input type=submit value=IN id=stampInBtn />
I have more code inside the View of course; divs, head, body, title and scripts. But it's perhaps a little irrelevant.
What should I do to successfully show those messages?
Regards.