из Dynami c html сообщение json ajax с mvc c# - PullRequest
0 голосов
/ 25 марта 2020

У меня проблема с отправкой данных из динамического c сгенерированного html в ASP. NET контроллера с использованием HttpClient. Проблема в том, что я публикую неверные данные JSON, я пропускаю генерацию правильных json на c#, потому что форма HTML не включает эту часть при генерации. я думаю, что должен иметь дело с вложенным json, но все еще не уверен, что произойдет. У меня есть JSON, откуда я генерирую HTML форму на ASP. NET ядре.

    "inputs": [
        {
            "inputs": [
                {
                    "inputs": [],
                    "type": "TEXT",
                    "description": null,
                    "name": "name",
                    "multiple": false
                }
            ],
            "type": null,
            "description": null,
            "name": "requestMemebershipInput",
            "multiple": false
        }
    ],
    "constraints": [
        {
            "name": "mandatory_requestMemebershipInput_name",
            "expression": "requestMemebershipInput?.name != null",
            "explanation": "name is mandatory for requestMemeber",
            "inputNames": [
                "requestMemebershipInput"
            ]
        }
    ]
}

Из этой формы JSON я генерирую динамику c html, которая имеет только одно текстовое поле. Для этой цели я использую 3 класса.

    public class Input2
    {
        [DataMember]
        [JsonProperty("inputs2")]
        public List<object> inputs { get; set; }
        [DataMember]
        public string type { get; set; }
        [DataMember]
        public object description { get; set; }
        [DataMember]
        [JsonProperty("name")]
        public string name { get; set; }
        [DataMember]
        public bool multiple { get; set; }
    }




    public class Input
    {
        [JsonProperty("inputs")]
        public IEnumerable<Input2> Input2 { get; set; }
        public object type { get; set; }
        public object description { get; set; }
        [JsonProperty("name")]
        public string name { get; set; }
        public bool multiple { get; set; }
    }
    public class ContractsInputViewModel
    {

        [JsonProperty("inputs")]
        public List<Input> Inputs { get; set; }
        [JsonProperty("constraints")]
        public List<object> constraints { get; set; }

    } ```


parsing and generating the form is done and everything it works ok , The problem strarts when i want to post the data using Httpclient to external url.
I tried postman only the following JSON  sends the data.

{"requestMemebershipInput": {"name": "test"
}}

"name" : "test" // this is the textbox on html ghenerated form
the problem is that when i generate form and pass data on controller i am passing only this format 
```{
  "requestMemebershipInput" : {
    "name" : "test"    
  }
}```

the controller i use for post has this Code 
```  [HttpPost]
        [AllowAnonymous]
        public async Task<ActionResult> Complexi(IFormCollection input2)
        {

            var url = await _bonitaClient.GetData();
            var id = TempData["id"];
            var collection = Request.Form.Keys.ToDictionary(k => k, v => Request.Form[v].ToString());



            using (var handler = new HttpClientHandler { UseCookies = false })
            {

                using (var client = new HttpClient(handler))
                {
                    var formContent = new Dictionary<string, string>
                            {
                              {"username", "walter.bates"},
                              {"password", "bpm"},
                              {"redirect", "false"}

                            };

                    var listdata = new Dictionary<string, string>();
                    foreach (var key in input2.Keys)
                    {
                        listdata.Add(key, input2[key]);
                        var value = input2[key];
                    }
                    var lista = Json(listdata);

                    client.BaseAddress = new Uri(url);

                    client.DefaultRequestHeaders.Clear();
                    //Define request data format  
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    //string ids = payload.value.id;
                    string urls = "API/bpm/process/" + id + "/instantiation";
                    string urlr = "API/bpm/process/" + id + "/contract";


                    var result = client.PostAsync("loginservice", new FormUrlEncodedContent(formContent)).Result;

                    // Variable to hold the authentication cookie.

                    // Get the authentication cookie from the login request.4904797668459909207 //6261660325251571593
                    var setCookie = string.Empty;
                    var message = new HttpRequestMessage(HttpMethod.Get, urlr);
                    var st = "";
                    foreach (var header in result.Headers.Where(header => header.Key == "Set-Cookie"))
                    {
                        foreach (var value in header.Value)
                        {
                            st += value + ";";
                        }
                        break; // We only care about the first match.
                    }

                    message.Headers.Add("Cookie", st);
                    //message.Content.Headers.Add("Cookie", st);

                    var Res = await client.SendAsync(message);


                    if (Res.IsSuccessStatusCode)
                    {


                        StringContent jsonp = new StringContent(JsonConvert.SerializeObject(lista), Encoding.UTF8, "application/json");
                        var processResponse =  Res.Content.ReadAsStringAsync().Result;



                        var t = await client.PostAsync(urls, jsonp);

                    }

                }
            }
            return Ok();
        }

AJAX Код

        $("#form1").on('submit', function (e) {
            e.preventDefault();
            var myHeaders = new Headers();
                myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
               urlencoded.append("username", "walter.bates");
               urlencoded.append("password", "bpm");
               urlencoded.append("redirect", "false");
            var formData = $('#form1').serialize();
            //console.log(formData);
            function getCookie(cname) {
            var name = cname + "=";
            var decodedCookie = decodeURIComponent(document.cookie);
            var ca = decodedCookie.split(';');
            for (var i = 0; i++;) {
                console.log(getCookie('X-Bonita-API-Token'));
                //catch(error => console.log('error', error));
            };
        };
            $.ajax({
                url: '/Contract/Complexi',
                headers: myHeaders,
                type: "POST",
                data: formData,
                redirect: 'follow',
                success: function (data) {
                    alert(data.message);
                    console.log(data);
                },
                error: function (xhr, resp, text) {
                    console.log(xhr, resp, text);
                }
            });
        });
        });```
...