【问题标题】:Pass javascript object with http post使用 http post 传递 javascript 对象
【发布时间】:2016-11-17 10:55:59
【问题描述】:

我正在尝试传递一个包含

的 javascript 对象
question(string), multianswers(answer(string),correct(bit)).

这就是多重​​答案的价值 -

[{'correct':true,'answer':'A1'}, {'correct':true,'answer':'A2'}];

我传递给控制器​​的参数应该是什么类型。

function setMultiQuestion(question, responses) {

    var responsesList = angular.toJson(responses);

    function questionAnswerObj(question, answers)
    {
        this.question = question;
        this.answers = answers;
    }

    qaObject = new questionAnswerObj(question, responsesList);

    $http.post(baseUrl + "Admin/insertMultiAnswers", { data: qaObject })
  .success(function (data, status, headers, config) {

      $mdDialog.hide();
      $mdToast.show(
      $mdToast.simple()
     .textContent('New question was added.')
     .position('top')
     .hideDelay(5000)
     .theme('success-toast')
     );
  })
  .error(function (data, status, header, config) {
  });
}

这是我的控制器。

 [HttpPost]
    public ActionResult insertMultiAnswers(object data)
    {
        try
        {
            Console.Write(data);
          //  data.setMultiAnswer();
            Response.StatusCode = 200;
            return Content("Sucess");
        }
        catch (Exception ex)
        {
            Response.StatusCode = 500;
            return Content("Fail");
        }
    }

【问题讨论】:

  • 你是否使用任何相同的类?

标签: javascript c# angularjs model-view-controller http-post


【解决方案1】:

我传递给控制器​​的参数应该是什么类型。

string[] data

这是由于[{'correct':true,'answer':'A1'}, {'correct':true,'answer':'A2'}];。括号表示数组。 {} 表示对象。所以你的数组由包含值的对象组成。

为了进一步操作控制器中的数组,我建议查看这些示例。 http://sarangasl.blogspot.nl/2014/01/pass-complex-javascript-object-to-mvc.html

例如,您可以创建一个包含布尔正确答案和字符串答案的类,并将控制器中数组中的对象转换为此类。这使得以后使用它们变得容易。简化此过程的插件示例是Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

编辑:

不确定你的函数做了什么,但它没有返回任何东西。尝试将其更改为:

function questionAnswerObj(question, answers)
{
    var object = {
                   question: question,
                   answers: answers
                 }
    return object;
}

var object = {} 创建一个新对象。由于函数没有返回任何内容,因此控制器中的参数为 null 是有道理的,这与 null 相同。如果应用这些更改,则必须将控制器中的参数类型替换为字符串,因为我们发送的不是数组而是对象。

【讨论】:

  • 谢谢。但对象包含 - question(string) + json array(correctAns(bit), answer(string))
  • 我听从了您的建议并更改了我的代码,例如: public ActionResult insertMultiAnswers(string[] data) 。但仍然为空。我没有更改 javascript 控制器中的任何内容。
  • 函数 questionAnswerObj(question, answers) { this.question = question; this.answers = 答案; }
  • 顺便说一下,json2csharp.com 是一个很好的工具,可以从 json 对象快速创建 c# 类,用于像 newtonsoft 这样的序列化程序。
猜你喜欢
  • 1970-01-01
  • 2018-10-07
  • 1970-01-01
  • 1970-01-01
  • 2012-09-14
  • 1970-01-01
  • 1970-01-01
  • 2011-08-06
  • 2016-09-14
相关资源
最近更新 更多