【问题标题】:How can send int and string with ajax to C#如何将带有 ajax 的 int 和 string 发送到 C#
【发布时间】:2013-12-27 16:36:32
【问题描述】:

我需要在C# 中向方法发布两个参数

 [HttpPost]
 public bool information([FromBody]int idInfromation,[FromBody] string information)
    {
       .....
       return true;
    }

使用ajax,但我的解决方案不起作用。 Newtwork 标签正在显示:

POST http://-----/information/SubmitAnswer 500(内部服务器错误)

我有这个:

var source = { "idInfromation": 5, "information": "Wau" };

$.ajax({
    url: "/information/",
    type: "POST",
    data: source,
    dataType: "json",
    contentType: "application/json",
    success: function (data) {
        alert("Complete");

    }

});

感谢您的建议。

【问题讨论】:

  • 您的操作正在引发异常。调试它并找出异常是什么。
  • 它点击 /information/SubmitAnswer 而不是您的信息操作。
  • 不,我只是重写了,对不起。但谢谢你的来信。 :)

标签: c# jquery asp.net-web-api


【解决方案1】:

您不能传递多个 [FormBody] 参数,而是必须将参数作为对象传递。 例如,声明一个 DTO 类

// DTO
public class InformationClass{
  public int idInfromation{ get; set; }
  public string Information{ get; set; }
}

[HttpPost]
 public bool information(InformationDTO Info)
    {
       .....
       return true;
    }

使用 Json ajax 传递对象:

// Initialize the object, before adding data to it.
//  { } is declarative shorthand for new Object().
var Information= { };

Information.idInfromation= ParseInt($("txtId").val()); // your desired value
Information.Information= $("#Information").val();

// Create a data transfer object (DTO) with the proper structure.
var DTO = { 'Information' : Information};

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "InformationService.asmx/information", // or your specified url, if you don't want //use service like url: "/information/",
  data: JSON.stringify(DTO),
  dataType: "json"
});

希望这会有所帮助, 谢谢。

【讨论】:

  • 我这样做了,但是当我调试这个解决方案时,DTO.Information.idInformation 是 1,但在控制器中 info.idInformation 是 0。我不明白它......跨度>
  • 使用 ajax 中的警报消息框检查 Information.idInfromation= ParseInt($("txtId").val()); // 你想要的值 Information.Information= $("#Information").val();看看你得到了什么。为整数类型的 id 和字符串类型文本字段的信息赋值,并检查你得到了什么警报。
  • 问题出在其他地方,但我找到并解决了。感谢您的建议。
【解决方案2】:

您不能使用 [FromBody] 返回两个值。创建 DTO 类或将其作为 JObject 接收。

【讨论】:

  • 现在,我尝试创建 DTO 对象,谢谢您的建议。 :)
猜你喜欢
  • 1970-01-01
  • 2012-02-24
  • 2017-09-08
  • 2019-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
相关资源
最近更新 更多