如何使用带有 JSON 结果的 Ajax.BeginForm MVC 助手? [英] How to use Ajax.BeginForm MVC helper with JSON result?

查看:30
本文介绍了如何使用带有 JSON 结果的 Ajax.BeginForm MVC 助手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 ASP.NET MVC Ajax.BeginForm 帮助程序,但不想在调用完成时使用现有的内容插入选项.相反,我想使用自定义 JavaScript 函数作为回调.

I'm trying to use the ASP.NET MVC Ajax.BeginForm helper but don't want to use the existing content insertion options when the call completes. Instead, I want to use a custom JavaScript function as the callback.

这可行,但我想要的结果应该作为 JSON 返回.不幸的是,该框架只是将数据视为字符串.下面是客户端代码.服务器代码只返回一个带有一个字段的 JsonResult,UppercaseName.

This works, but the result I want should be returned as JSON. Unfortunately, the framework just treats the data as a string. Below is the client code. The server code simply returns a JsonResult with one field, UppercaseName.

<script type='text/javascript'>
    function onTestComplete(content) {
        var result = content.get_data();
        alert(result.UppercaseName);
    }
</script>

<% using (Ajax.BeginForm("JsonTest", new AjaxOptions() {OnComplete = "onTestComplete" })) { %>
    <%= Html.TextBox("name") %><br />
    <input type="submit" />
<%} %>

不是显示大写结果,而是显示未定义.content.get_data() 似乎包含 JSON,但仅以字符串形式保存.如何将其转换为对象?

Instead of showing the uppercase result, it is instead showing undefined. content.get_data() seems to hold the JSON, but only in string form. How do I go about converting this to an object?

所有这些看起来真的有点令人费解.有没有更好的方法来使用 Ajax.BeginForm 获取结果内容?如果真的这么难,我可能会完全跳过 Ajax.BeginForm,直接使用 jQuery 表单库.

All of this seems a bit convoluted really. Is there a better way to get at the resulting content using Ajax.BeginForm? If it's this hard, I may skip Ajax.BeginForm entirely and just use the jQuery form library.

推荐答案

试试这个:

var json_data = content.get_response().get_object();

这将为您提供 JSON 格式的结果,您可以使用 json_data[0] 获取第一条记录

this will give you result in JSON format and you can use json_data[0] to get the first record

这篇关于如何使用带有 JSON 结果的 Ajax.BeginForm MVC 助手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆