【问题标题】:How to pass a C# object to $.ajax如何将 C# 对象传递给 $.ajax
【发布时间】:2013-07-13 06:12:42
【问题描述】:

我有简单的 JavaScript 代码,我想在其中从控制器获取对象并在脚本中解析它,但在脚本中,我无权访问对象的任何属性。

我的对象(在控制器中):

public class userData
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public string state { get; set; }
    public bool success { get; set; }
}

脚本:

function  load()
{
    var sender = {
         userNo : $("#userNo").val(),
    }
    $.ajax({
        type : "POST",
        url : "testGetUser",
        data : sender,
        success:function(data)
            {
                if(1)
                {
                    $("#section #result0").html(data.firstName);
                    $("#section #result1").html(data.lastName);
                    $("#section #result2").html(data.state);
                    $("#section").slideDown().delay(1000).slideUp();
                }
            }
    });
}

控制器:

[HttpPost]
public userData testGetUser(long userNo)
{
    userData result = new userData();

    result.firstName = Session["firstName"].ToString();
    result.lastName = Session["lastName"].ToString();
    result.state = Session["country"].ToString();
    result.success = true;

    return result;
}

【问题讨论】:

标签: c# javascript jquery ajax asp.net-mvc


【解决方案1】:

在控制器中,使用这个:

[HttpPost]
public JsonResult testGetUser(long userNo)
{
    userData result = new userData();

    result.firstName = Session["firstName"].ToString();
    result.lastName = Session["lastName"].ToString();
    result.state = Session["country"].ToString();
    result.success = true;

    return Json(result);
}

您似乎没有使用变量userNo,所以您最好使用这样的GET请求:

public JsonResult testGetUser(/*remove parameter*/)
{
    userData result = new userData();

    result.firstName = Session["firstName"].ToString();
    result.lastName = Session["lastName"].ToString();
    result.state = Session["country"].ToString();
    result.success = true;

    return Json(result, JsonRequestBehavior.AllowGet);
}

JavaScript 现在想要这样:

function  load()
{
    $.ajax({
        type : "GET",
        url : "testGetUser",
        success:function(data) {
            $("#section #result0").html(data.firstName);
            $("#section #result1").html(data.lastName);
            $("#section #result2").html(data.state);
            $("#section").slideDown().delay(1000).slideUp();
        }
    });
}

【讨论】:

  • 另一个旁注:由于页面上的元素 id 应该是唯一的,因此将多个 id 传递给选择器是一种不好的做法,直接$("#result0") 在选择器解析中会更快,在节点中会更快搜索。
猜你喜欢
  • 2023-03-11
  • 1970-01-01
  • 2018-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-09
  • 2015-03-01
  • 1970-01-01
相关资源
最近更新 更多