【问题标题】:Cannot Pass JSON Result back to View无法将 JSON 结果传递回视图
【发布时间】:2015-02-07 13:37:04
【问题描述】:

我有以下 HTML 来显示一些消息

...
<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>
...

按下按钮时触发的脚本是

<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>

然后在我的控制器中我有

[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);
}

控制器方法触发,发送电子邮件并返回视图,但未显示我的消息。 如何让标签显示正确的文本?

感谢您的宝贵时间。


注意。我见过

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

但这些对我没有帮助。

【问题讨论】:

  • 我相信当你做Json(new { a = 1, b = 1})时,javascript函数处理程序应该是function(data) { var a = data.a; var b = data.b}。即,js 处理程序应该只有一个参数。尝试在你的处理程序中做一个console.log(result_success);,看看你真正得到了什么
  • 感谢大家的回答。非常感谢您的所有时间...

标签: javascript asp.net-mvc json asp.net-mvc-5


【解决方案1】:

JavaScript 必须是这样的:

<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>

注意success函数显示只有一个参数被传入:result

这是因为在你的操作中你返回了这个:

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

您创建一个新对象:new {},然后用一些字段填充它。因此,当它被发送回页面时,将有一个具有两个属性的对象 (result)。显然,返回的对象不称为result,但这是在您的函数上下文中赋予它的名称。

最后,因为您使用的是return Json,您还应该确保您的Action 方法返回类型JsonResult 而不是ActionResult。在后台 ASP.NET 团队扩展了ActionResult,但他们还设置了一些属性,如内容类型,以确保网页知道如何处理响应。它还使用 JavaScript 序列化器正确序列化对象。参考:http://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.Mvc/JsonResult.cs

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

如果您想使用 newtonsoft JSON.net,我会创建您的自定义结果来实现它。

【讨论】:

    【解决方案2】:

    改变你的成功方法

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

    服务器返回一个 json 对象。

    【讨论】:

    • 是的,绝对同意这一点,但是,您能否指出您应该返回 JsonResult 而不是 ActionResult ....
    【解决方案3】:

    尝试将您的 ajax 成功处理程序更改为类似

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

    处理程序应该收到一个 JSON 对象,其中包含您在操作中指定的 2 个属性。

    【讨论】:

      【解决方案4】:

      你必须使用这个

      <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>
      

      【讨论】:

      • 那不行,因为success函数只有一个对象作为参数,不是两个!
      【解决方案5】:
      $('#fail_message').html(result.result_failure);
      $('#success_message').html(result.result_success);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多