Qvadriologic
Qvadriologic

Reputation: 85

Returning Json Data From Controller to View ASP.NET MVC

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.

Upvotes: 1

Views: 17749

Answers (3)

Sujit Patil
Sujit Patil

Reputation: 183

Change your javascript code as following:

            $(document).ready(function () {

        $("#stampInBtn").click(function () {

        var userId = $("#userId").val();

            $.ajax({
                url: "ComeAndGo/CreateStamp",
                type: "POST",
                dataType: "json",
                data: {
                    userId: userId,
                },
                success: function(data) {
                var objData= jQuery.parseJSON(data);
                alert(objData.Message );
                },
                error: function (request, status, error) {
                    alert(request.responseText);
                }

            });

        });
    });

Upvotes: 0

user3559349
user3559349

Reputation:

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

Upvotes: 1

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18431

You are getting the value of $("#userId"), but your input has an id of idUser.

Try making your input:

<input type="text" id="userId" class="form-control" />

Also it would be a good idea to provide your Stamping model structure as it seems that you only pass the user id in your post and nothing else.

Upvotes: 0

Related Questions