【问题标题】:Reading Javascript FormData value in Asp.net Web api Httpresponsemessage在 Asp.net Web api Httpresponsemessage 中读取 Javascript FormData 值
【发布时间】:2017-11-14 08:34:56
【问题描述】:

我有一个用 [HttpPost] 装饰的 Web api,用于上传参数中传递的所有信息,但出现此错误

错误

控制器

  [HttpPost]
   public HttpResponseMessage questionnairesubmit(HttpRequestMessage form)
    {

     //want to get json of "questionlist" which is send from javascript like
      var QuestionnaireList = JsonConvert.DeserializeObject<List<outRightLogos.Areas.client.WebApiModel.AttributeValueTB>>(form["questionlist"]);


    }

这是 javascript 发送名称为 questionlist 的 Json 模型,我想在控制器中获取它。我从 Here 读取 FormData()

Javascript

var data = new FormData();
var QuestionnaireList = [];
 QuestionnaireList.push({

            FieldID: $(this).attr("data-fieldid"),
            attributeID: $(this).attr("data-attributeid"),
            attributeValue: $(this).val(),
            websitesID: 2,
            OrderID: $('#orderid').val(),
            orderbitID: $('#orderbidid').val(),
            serviceId: $(this).attr("data-serviceid"),
            subServiceId: $(this).attr("data-subserviceid"),
            IsSubmit: IsSubmit,
        });

data.append("questionlist", JSON.stringify(QuestionnaireList));
$.ajax({
                    type: "POST",
                    url: path,
                    contentType: 'application/json',//"application/json; charset=utf-8",
                    processData: false,
                    dataType: "json",
                    data: data,

                    success: function (result) {

                        if (result.sucess == "save") {
                            alert('Your form has been saved.');

                        }
                        else if (result.sucess == "Submit") {
                            alert('Your form has been submitted.');
                            window.location.href = result.Url;
                        }
                    },
                    error: function (result) {
                        alert('Oh no ');
                    }

                });

这里是一个模型类AttributeValueTB

 public class AttributeValueTB
{
    public long attributeValueID { get; set; }

    [Required]
    [StringLength(200)]
    public string attributeValueCode { get; set; }

    public int FieldID { get; set; }

    public int attributeID { get; set; }

    public string attributeValue { get; set; }

    public int websitesID { get; set; }

    public long OrderID { get; set; }
    public long orderbitID { get; set; }
    public long serviceId { get; set; }
    public long subServiceId { get; set; }
    public string extra1 { get; set; }
    public string extra2 { get; set; }
    [StringLength(200)]
    public string attributeCode { get; set; }
    public bool isActive { get; set; }

    public bool isShow { get; set; }
    public bool IsSubmit { get; set; }

    [Column(TypeName = "date")]
    public DateTime? createDate { get; set; }

    [Column(TypeName = "date")]
    public DateTime? modifiedDate { get; set; }

    public int? createBy { get; set; }

    public int? modifiedBy { get; set; }

    [Column(TypeName = "timestamp")]
    [MaxLength(8)]
    [Timestamp]
    public byte[] Timestamp { get; set; }
}

【问题讨论】:

    标签: javascript c# json asp.net-mvc asp.net-web-api2


    【解决方案1】:

    你不需要手动序列化任何东西,只要你在 C# 中提供了一个模型类。

    Json.NET 非常聪明,会自动序列化您的参数。

    [HttpPost]
    public HttpResponseMessage QuestionnaireSubmit(AttributeValueTB form)
    {
       // Form is serialized and can be used here       
    
    }
    

    如果您也想读取 cookie,可以在此方法中使用 Request.Cookies

    【讨论】:

      【解决方案2】:

      您需要从“jsoncontent”而不是“form”收集信息

      HttpContent requestContent = Request.Content;
      string jsonContent = requestContent.ReadAsStringAsync().Result;
      entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
      

      如果您使用类对象作为参数也适用于您的上下文,则需要像这样更改方法。

      [HttpPut]
      public HttpResponseMessage Put(int id)
      {
        HttpContent requestContent = Request.Content;
        string jsonContent = requestContent.ReadAsStringAsync().Result;
        entityclass obj= JsonConvert.DeserializeObject<entityclass>(jsonContent);
        ...
      }
      

      【讨论】:

      • 你遇到什么错误?检查您的 jsoncontent 您需要的内容是否存在
      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      相关资源
      最近更新 更多