I am developing a .NET application where users can go fill out a request (form). Once the user clicks "Submit". The goal is to send a POST request to a function app (PowerShell powered). If the post request is successful, it would return a id for the request.
I would like to use this Id to query the status of the request (GET) sent to the function app. Once a user hits submit, it should automatically redirect them to the details page where they can view their request status.
Here is my controller I want to route the request to:
namespace AzDeployManager.Web.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class DeploymentController : ControllerBase
{
public string ReceiveRequest { get; set; }
public string CheckRequest { get; set; }
public DeploymentController(IOptions<AppSettings> settings)
{
this.ReceiveRequest = settings.Value.AzReceiveRequest;
this.CheckRequest = settings.Value.AzCheckRequest;
}
// POST: api/ReceiveRequest
[HttpPost]
[Route("sendrequest")]
public async Task<IActionResult> OnPostAsync([FromBody] Deployment deployment)
{
using var http = new HttpClient();
var data = new Deployment
{
};
//var content = new StringContent(JsonConvert.SerializeObject(deployment));
var content = new StringContent(JsonConvert.SerializeObject(data));
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var request = http.PostAsync(ReceiveRequest, content);
var response = await request.Result.Content.ReadAsStringAsync();
return Ok(response);
}
}
}
In my http post shown in the controller, I am able to view the data by debugging. I am now having issues customizing the payload as I want it:
{
"data": {
"name1": "val1",
"name2": "val2"
},
"name3": "val3"
}
Any guidance will be helpful here.
CodePudding user response:
You can use jQuery to serialize the key-value pairs of the form into an array, then parse it into a json object.
<script>
function getdata() {
var paramArray = $('#submitreq').serializeArray();
var body = {};
$(paramArray).each(function () {
//here
if (this.name.indexOf('\.') > 0) {
body[this.name.split('\.')[1]] = this.value;
} else {
body[this.name] = this.value;
}
});
body['RequestNumber'] = parseInt(body['RequestNumber'])
$.ajax({
type: "POST",
url: "/api/sendrequest",
dataType: "json",
data: JSON.stringify(body),
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log("Success: " response.RequestNumber);
},
error: function (req, status, error) {
console.log("Error occured: " status "" req.responseText);
}
});
}
</script>
Because the fieldset is set to disabled, it will not be automatically serialized, you can add a hidden input box outside the fieldset.
<form id="submitreq" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Deployment.RequestNumber" class="form-control" />
<!--...-->
<input type="button" name="name" value="submit" onclick="getdata()" />
</form>

