Thursday, May 23, 2024
Homepage · c#
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  14] [ 2]  / answers: 1 / hits: 17298  / 10 Years ago, mon, september 22, 2014, 12:00:00

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.


More From » c#

 Answers
41

Add a success function to the ajax call



$.ajax({
url: ComeAndGo/CreateStamp,
type: POST,
dataType: json,
data: { userId: userId },
success: function(data) {
// data contains the value returned by the server
console.log(data);
}
});


So if the controller returns



return Json(This is a message);


the value of data will be This is a message. Note the return value can be a complex type or a partial view


[#69376] Thursday, September 18, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
melinal

Total Points: 367
Total Questions: 101
Total Answers: 96

Location: Nauru
Member since Thu, Feb 2, 2023
1 Year ago
melinal questions
Thu, Dec 2, 21, 00:00, 3 Years ago
Tue, Jun 15, 21, 00:00, 3 Years ago
Tue, Feb 25, 20, 00:00, 4 Years ago
;