0

I have the following HTML to show some messages

...
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <span id="fail_message" class="label label-danger"></span>
        <span id="success_message" class="label label-success"></span>
    </div>
</div>
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="button" value="Invite User" class="btn btn-primary"/>
    </div>
</div>
...

The script that fires when the button is pressed is

<script>
    $(function () {
        $("input[type=button]").click(function () {
            var data_email = $('#email').val();
            var data_product = $('#product option:selected').text();
            $.ajax({
                url: 'Tools/SendInvite',
                type: 'POST',
                data: { email: data_email, product: data_product },
                success: function (result_success, result_failure) {
                    $('#fail_message').val(result_failure);
                    $('#success_message').val(result_success);
                }
            });
        });
    });
</script>

Then in my controller I have

[AllowAnonymous]
public async Task<ActionResult> SendInvite(
    string email, string product)
{
    // Check if admin.
    ApplicationUser user = null;
    if (ModelState.IsValid)
    {
        user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        if (user.IsAdmin != null && (bool)user.IsAdmin)
        {
            string key = String.Empty;
            string subMsg = String.Empty;
            var accessDB = new AccessHashesDbContext();
            switch (product) { /* do stuff */ }

            // Send email.
            try
            {
                await Helpers.SendEmailAsync(new List<string>() { email }, null, "my msg string" );
                result = String.Format("Invitation successfully sent to \"{0}\"", email);
                return Json(new {
                        result_success = result,
                        result_failure = String.Empty
                    },
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception)
            {
                result = String.Format("Invitation to \"{0}\" failed", email);
                return Json(new {
                        result_success = String.Empty,
                        result_failure = result
                    },
                    JsonRequestBehavior.AllowGet);
            }
        }
    }
    return Json(new {
            result_success = String.Empty,
            result_failure ="Invite Failure"
        },
        JsonRequestBehavior.AllowGet);
}

The controller method fires, the email is sent and the view gets returned to, but my messages are not shown. How can I get the lables to display my correct text?

Thank for your time.


Note. I have seen

  1. ASP.NET MVC controller actions that return JSON or partial html
  2. how to set textbox value in jquery

but these do not help me.

Community
  • 1
  • 1
MoonKnight
  • 23,214
  • 40
  • 145
  • 277
  • I believe when you do `Json(new { a = 1, b = 1})`, the javascript function handler should be `function(data) { var a = data.a; var b = data.b}`. I.e., the js handler should only have one parameter. try doing a `console.log(result_success);` in your handler to see what you're really getting back – DLeh Dec 09 '14 at 15:33
  • Thanks to everyone for their answers. All of your time is most appreciated... – MoonKnight Dec 09 '14 at 18:26

5 Answers5

1

change your success method with following

success: function (result) {
    $('#fail_message').html(result.result_failure);
    $('#success_message').html(result.result_success);
}

server return one json object.

AliRıza Adıyahşi
  • 15,658
  • 24
  • 115
  • 197
  • Yeah definately agree with this one, however, could you also make the point that you should return `JsonResult` rather than `ActionResult` .... – Callum Linington Dec 09 '14 at 15:45
1

Try changing your ajax success handler to something like

  function (result) {
       $('#fail_message').html(result.result_failure);
       $('#success_message').html(result.result_success);
   }

The handler should receive a JSON object with the 2 properties you specified in your action.

dustyhoppe
  • 1,783
  • 16
  • 20
1
$('#fail_message').html(result.result_failure);
$('#success_message').html(result.result_success);
Scimonster
  • 32,893
  • 9
  • 77
  • 89
dotnetstep
  • 17,065
  • 5
  • 54
  • 72
1

you must use this

<script>
    $(function () {
        $("input[type=button]").click(function () {
            var data_email = $('#email').val();
            var data_product = $('#product option:selected').text();
            $.ajax({
                url: 'Tools/SendInvite',
                type: 'POST',
                data: { email: data_email, product: data_product },
                success: function (result) {
                         $('#fail_message').html(result.result_failure);
                         $('#success_message').html(result.result_success);
                }
            });
        });
    });
</script>
Danny Rancher
  • 1,923
  • 3
  • 24
  • 43
1

The JavaScript needs to be this:

<script>
    $(function () {
        $("input[type=button]").click(function () {
            var data_email = $('#email').val();
            var data_product = $('#product option:selected').text();
            $.ajax({
                url: 'Tools/SendInvite',
                type: 'POST',
                data: { email: data_email, product: data_product },
                success: function (result) {
                    $('#fail_message').html(result.result_failure);
                    $('#success_message').html(result.result_success);
                }
            });
        });
    });
</script>

Note that the success function shows that there is only one parameter being passed in: result.

This is because in your action you return this:

return Json(new {
            result_success = String.Empty,
            result_failure ="Invite Failure"
        },
        JsonRequestBehavior.AllowGet);

You create a new object: new {} then poulate it with some fields. Therefore when it gets sent back to the page there will be one object (result) with two properties. Obviously the object returned isn't called result, but that is the name given to it in the context of your function.

Lastly, because you are using return Json you should also make sure that your Action method returns the type JsonResult not ActionResult. Under the hood ASP.NET team extend the ActionResult but they also set up some properties like content type to make sure the web page knows how to handle the response. Also it uses the JavaScript serialiser to serialise the object correctly. Reference: http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/JsonResult.cs

public async Task<JsonResult> SendInvite(
    string email, string product)
{

If you want to use newtonsoft JSON.net I would create your Custom result that implements it.

Callum Linington
  • 14,213
  • 12
  • 75
  • 154