Pass IEnumerable<HttpPostedFileBase> to Webservice - javascript

I have found a few things that are similar but now quite showing how to do it.. and I'm having problems adopting what I've found to my situation. I'm trying to pass multiple images and text to a webservice to then save to db/amazon.
This is what I have so far...
The Form
<form class="create-status" enctype="multipart/form-data">
<div class="row">
<div class="col-sm-12">
#Html.TextAreaFor(model => model.status, new { cols = "1", rows = "1", #class = "form-control no-max-width input-sm", id = "tbStatus", placeholder = "Beep Here", req = "tbStatus" })
</div>
</div>
<div class="row collapse" id="divStatusInputs">
<br />
<div class="col-sm-6">
<div class="row">
<div class="col-sm-3">
<a class="icon"><span id="spanImageInput" class="glyphicon glyphicon-camera glyphicon-camera-input icon"></span></a>
<input id="imageInput" multiple type="file" class="hidden" name="files" />
</div>
</div>
</div>
<div class="col-sm-6 text-right">
<div class="text-right">
<button id="btnCancel" class="btn btn-default" type="button">Cancel</button>
<a id="aSubmitStatus" class="btn btn-primary">Submit</a>
<input id="btnSubmitStatus" type="submit" class="btn hidden" />
</div>
</div>
</div>
</form>
And the jQuery/Javascript..
function CreateStatus() {
var status = $('#tbStatus').val();
var formData = new FormData();
var data = {
files: "", //this is where i'm having the issue? I'm not sure what to do here.
status: status
}
$.ajax({
type: 'POST',
url: '/Webservices/StatusWebService.asmx/CreateStatus',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
console.log(result.d);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
}
And the webservice
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public async Task<string> CreateStatus(string status, IEnumerable<HttpPostedFileBase> files)
{
//everything here needed to save to db/amazon s3
}
If I remove the HttpPostedFileBase and associated code, I'm able to call the webservice just fine, just having issues passing the proper files/images to the webservice.
Any help is greatly appreciated!!

Related

How to store imported files through input in a list temporary and then pass the list to post request using Javascript or jQuery?

I want to use this list because before submitting I might remove a few and add more files to the list. When I use the input to get the files it has only the last imported files, not the previous ones but I want to preserve the previous ones as well cause I want to add or subtract images or pdf files to list before submission.
HTML Code:
//<form method="POST" id="medical_record_form" enctype="multipart/form-data" '>
<div class="card">
<div class="card-body">
<div class="row form-row">
<div class="col-12 col-md-12">
<div class="form-group">
<label>Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Medical Documents</label>
<div class="upload-img">
<div class="change-photo-btn">
<span><i class="fa fa-upload"></i> Upload File</span>
<input id="medical_documents" name="medical_documents"
type="file" multiple accept="image/*,.pdf"
onchange="readURL(this);" class="upload">
</div>
<small class="form-text text-muted">All Image Types Are Allowed, Plus
PDF Files</small>
</div>
</div>
<div class="upload-wrap" id="documets_wrapper">
<!-- the images preview goes here which is handled by javascript -->
</div>
</div>
</div>
</div>
</div>
<div class="submit-section">
<button type="submit" id="medical_submit_button" class="btn btn-primary submit-btn">Save
Changes</button>
</div>
</form>
Javascript code:
'''
// Fields
const medicalForm = document.getElementById('medical_record_form');
const title = document.getElementById('title');
const medicalDocuments = document.getElementById('medical_documents');
var filesList = [];
function readURL(input) {
if (input.files && input.files[0]) {
for (let i = 0; i < input.files.length; i++) {
filesList.push(event.target.files[i]); // not working
var tempHtml = '<div class="upload-images" id="image_' + i + '">' +
'<img src="' + URL.createObjectURL(event.target.files[i]) + '" alt="Upload Image">' +
'<i class="far fa-trash-alt"></i>' +
'</div>';
$('#documets_wrapper').append(tempHtml);
}
}
}
$("#medical_submit_button").on('click', function () {
medicalForm.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('csrfmiddlewaretoken', theToken);
formData.append('title', title.value);
formData.append('medical_documents', filesList);
$.ajax({
type: 'POST',
url: addUrl,
contentType: false,
// contentType: 'multipart/form-data', // tried this one also
processData: false,
data: formData,
success: function (response) {
console.log('value of response');
console.log(response);
},
error: function (error) {
console.log('error: ', error);
},
cache: false,
contentType: false,
processData: false,
});
})
})
'''

Javascript, Ajax : Bad Request 400

I'm working on ASP Net Core Project and I'm trying to send to my controller with JQuery Ajax function from a partial view modal, parameters.
The recovered URL is correct for example : http://localhost:44321/Validations/ValidationRefuse?ficheId=24&commentaire=Commentaire%20de%20test
But it's always :
Failed to load resource: the server responded with a status of 400 (Bad Request)
My Javascript :
$("#buttonRefusFiche").click(function (e) {
ficheId = $("#ficheId").val();
commentaire = $("#inputCommentaire").val();
$.ajax({
url: "/Validations/ValidationRefuse?ficheId=" + ficheId + "&commentaire" + commentaire,
type: 'POST',
contentType: 'application/html',
cache: true,
success: function () {
alert("Validation refusée.");
},
error: function () {
}
})
});
My C# method :
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ValidationRefuse(int ficheId, string commentaire)
{ ... }
My Partial View :
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Validez-vous cette fiche ?</h5>
<button type="button" class="btn btn-outline-dark btn-circle" data-dismiss="modal" aria-label="Close">
<i class="fa fa-close"></i>
</button>
</div>
<form asp-controller="Validations" asp-action="ValidationParResponsable" asp-route-id="#Model.FicheId" asp-route-eId="#Model.EnseignantId">
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="ficheId" asp-for="FicheId" />
<input type="hidden" asp-for="EnseignantId" />
<input type="hidden" asp-for="EtatId" />
<label class="control-label font-weight-bold">Commentaire :</label>
<textarea class="form-control" id="inputCommentaire" asp-for="Commentaire" placeholder="Votre commentaire"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" id="buttonRefusFiche">Refuser</button>
<button type="submit" class="btn btn-success">Valider</button>
</div>
</form>
I hope it's understandable, thanks for your responses. :)
When you use a POST request you have to send the parameters in the body of the request, not in the URL like that :
$("#buttonRefusFiche").click(function (e) {
ficheId = $("#ficheId").val();
commentaire = $("#inputCommentaire").val();
$.ajax({
url: "/Validations/ValidationRefuse",
type: 'POST',
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
dataType : "html",
data : {
ficheId : ficheId,
commentaire : commentaire
},
cache: true,
success: function () {
alert("Validation refusée.");
},
error: function () {
}
})
});
I also changed the contentType and added dataType.
For more information about ajax Post see documentation

AntiforgeryToken generation from using #Ajax.BeginForm()

I have an issue in generating anti-forgery token manually inside ajax methods. So my question If I used ajax.beginform(), does it generate a token like the #html.beginform? If so, how can I use it with my ajax methods?
Kindly ignore the long code in the view. My main concern is with the ajax methods. I posted it to show you the view in case of the suggestion of using the beginForm().
#*#Html.AntiForgeryToken()*#
<hr />
<div class="row">
<div class="col-lg-6">
<label><strong>Month:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Issue_Date</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label><strong>Count:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Count</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label><strong>Location:</strong></label>
</div>
<div class="col-lg-6">
<label>#manning_HQ.Location_Name</label>
</div>
</div>
<hr />
<div class="col-lg-4">
<label>Recruitment Status :</label>
</div>
<div class="col-lg-3">
<select id="recruitment_Status">
<option value="0">
Choose Status
</option>
#foreach (TBL_Recruitment_Status rec in recruitment_Status)
{
<option value="#rec.Rec_Status_ID">
#rec.Status_Name
</option>
}
</select>
</div>
<div class="row">
<div class="col-lg-12">
<label><strong>Issue staff requisition:</strong></label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<input type="radio" name="Decision" id="_123" value="Accepted" />
Accepted
</div>
<div class="col-lg-6">
<input type="radio" name="Decision" id="_456" value="Rejected" />
Rejected
</div>
</div>
<hr />
<div class="row" id="RejComment" hidden>
<div class="col-lg-6">
<label>Rejected Comment :</label>
</div>
<div class="col-lg-3">
<textarea id="RetainedComment"></textarea>
</div>
</div>
<br />
<div class="modal-footer" id="Save_Dicision" hidden>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="saveDecision(#manning_HQ.Issue_Staff_ID)">Save</button>
</div>
<script>
var DecesionCheck = false;
var rejected = false;
var reason = false;
$(document).ready(function () {
$('input[type=radio][name=Decision]').change(function () {
if ($("input[name='Decision']:checked").val() == 'Accepted') {
$('#RejComment').hide();
$('#Save_Dicision').show();
rejected = true;
}
if ($("input[name='Decision']:checked").val() == 'Rejected') {
$('#RejComment').show();
$('#Save_Dicision').show();
rejected = true;
}
});
});
function saveDecision(ID) {
var Decsion = $('input[name=Decision]:checked').val();
var Reason = $('#recruitment_Status').val();
//var token = $("[name='__RequestVerificationToken']").val();
if (Decsion == "#_123") {
if (DecesionCheck == true) {
var Decsion = $('input[name=Decision]:checked').val();
var optionalComment = $('#OptionalComment').val();
$.ajax({
type: 'POST',
url: '/Staff_Requisition_HQ/Recruitment_Actions',
data: {
// __RequestVerificationToken: token,
Issue_Staff_ID: ID,
Rec_Status_ID: Reason,
OpComment: RetainedComment,
RecDecison: Decsion,
},
success: function (result) {
$('#DescionDetailsPOPUP').modal('hide');
location.reload();
},
fail: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
}
}
else {
var Decsion = $('input[name=Decision]:checked').val();
var RetainedComment = $('#RetainedComment').val();
$.ajax({
type: 'POST',
url: '/Staff_Requisition_HQ/Recruitment_Actions',
data: {
//__RequestVerificationToken: token,
Issue_Staff_ID: ID,
Rec_Status_ID: Reason,
Comment: RetainedComment,
RecDecison: Decsion,
},
success: function (result) {
$('#DescionDetailsPOPUP').modal('hide');
location.reload();
},
fail: function (xhr, textStatus, errorThrown) {
alert('request failed');
}
});
}
}
</script>
Here's an example of Ajax.BeginForm from one of my views:
<!-- FORM Atributo -->
#using (Ajax.BeginForm(accionFormulario, "Atributos", new AjaxOptions() { OnSuccess = "onSuccessCreate" }, new { #id = "frmCreate" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.AtributoId)
#Html.HiddenFor(model => model.EmpresaId)
<div class="modal-body">
<div class="row">
// the form inputs ....
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary mx-1" type="button" data-dismiss="modal" aria-label="Close">#Global.Cancelar</button>
<button class="btn btn-primary" type="submit"><strong>#Global.Guardar</strong></button>
</div>
}
This generates the AntiForgeryToken as expected:
You can capture it with javascript as you were doing in your view.

How to submit form in jquery

This maybe a simple problem, but I can't find the cure.
When I executes this :-
$('#save_results').on("click", function () {
$('#formSaveQuotationPrepDetail').submit();
});
Everything works fine. But when I do this :-
$('#save_results').on("click", function () {
$('#formSaveQuotationPrepDetail').submit(function (e) {
var result = '#TempData["StatusMsg"]';
e.preventDefault();
if (result == 'Success') {
alert("Saved Successfully.");
}
})
});
This is my code behind :-
[HttpPost]
public ActionResult SaveQuotePreparation(QuotationPreparationEntity quoteP)
{
string result = objManager.SaveQuotePreparation(quoteP);
if (!string.IsNullOrEmpty(result) && (result == GeneralConstants.Inserted || result == GeneralConstants.Updated))
{
//Payment Gateway
data = GeneralConstants.SavedSuccess;
TempData["StatusMsg"] = "Success";
}
return new JsonResult { Data = data, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My HTML is a long code , I've made it short just for understanding :-
#using (Html.BeginForm("SaveQuotePreparation", "Technical", FormMethod.Post, new { #id = "formSaveQuotationPrepDetail" }))
{
<div class="row">
<form>
<div class="col-md-12 text-left">
<div class="row text-center">
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label ">
Quote Number
</label>
#Html.DropDownListFor(m => m.QuoteNo, new SelectList(#ViewBag.ListQuoteNo, "DataStringValueField", "DataTextField", Model.QuoteNo),
new
{
#class = "form-control requiredValidation",
#id = "QuoteNo",
#data_inneraction = "validationCall",
#onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)"
})
<span class="HideValidMsg">Please Select QuoteNo</span>
</div>
</div>
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label">
Product Line
</label>
#Html.DropDownListFor(m => m.ProductLine, new SelectList(#ViewBag.ListProdGrp, "DataStringValueField", "DataTextField", Model.ProductLine),
new
{
#class = "form-control requiredValidation",
#id = "ProductLine",
#onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)",
ng_model = "ProductLine",
ng_change = "GetProductLineDetails(ProductLine)"
})
<span class="HideValidMsg">Please Select ProductLine</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4 text-center">
<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results">Save</button>
#*<input style="font-size:18px" type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results" value="Save" />*#
<input style="font-size:18px" type="button" class="btn btn-secondary btn-sm" data-dismiss="modal" value="Close" />
</div>
</div>
</form>
The Event don't fire on click. I don't get any error or anything.
I want to return JSON data on submit and show it as an alert on the screen.
You can do form submit in javascript like this..
$(document).on("submit", "form", function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status) {
successFunction()
}
},
error: function (xhr, desc, err) {
}
});
});
The From will define like this
<form class="form-horizontal" id="frm" name="frm" action="/Controler/Action" method="post" enctype="multipart/form-data"></form>
And Need to create the button as submit
<input type="submit"/>
i dont have your html code but ,
if you want your form to be submitted by on click event :
$('#save_results').on("click", function () {
e.preventDefault();
$('#formSaveQuotationPrepDetail').submit();
if (result == 'Success') {
alert("Saved Successfully.");
}
});
take a look at this example to see difference between your first and second code .
NOTE : in your code result is not defined , i am not sure where have you brought it from
You did mistake in view page. Please remove <form> tag inside view page. It will work.
You only use below code instead of your code:
note: Html.Beginform() method work as tag in HTML
#using (Html.BeginForm("SaveQuotePreparation", "Technical", FormMethod.Post, new { #id = "formSaveQuotationPrepDetail" }))
{
<div class="row">
<div class="col-md-12 text-left">
<div class="row text-center">
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label ">
Quote Number
</label>
#Html.DropDownListFor(m => m.QuoteNo, new SelectList(#ViewBag.ListQuoteNo, "DataStringValueField", "DataTextField", Model.QuoteNo), new { #class = "form-control requiredValidation", #id = "QuoteNo", #data_inneraction = "validationCall", #onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)" })
<span class="HideValidMsg">Please Select QuoteNo</span>
</div>
</div>
<div class="col-md-4">
<div class="form-group text-left">
<label class="control-label">
Product Line
</label>
#Html.DropDownListFor(m => m.ProductLine, new SelectList(#ViewBag.ListProdGrp, "DataStringValueField", "DataTextField", Model.ProductLine), new { #class = "form-control requiredValidation", #id = "ProductLine", #onfocusout = "return ValidateRequiredFieldsOnFocusOut(this)", ng_model = "ProductLine", ng_change = "GetProductLineDetails(ProductLine)" })
<span class="HideValidMsg">Please Select ProductLine</span>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-4 text-center">
<button type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results">Save</button>
#*<input style="font-size:18px" type="button" class="btn btn-success btn-sm" data-dismiss="modal" id="save_results" value="Save" />*#
<input style="font-size:18px" type="button" class="btn btn-secondary btn-sm" data-dismiss="modal" value="Close" />
</div>
</div>
</div>
}

Wiki API request not working

I used some sample code from the Wiki API docs but when I enter a search item, nothing happens. No errors in the console, just nothing. The URL itself works if I enter it into a browser so I think something with the code is not passing in the proper value. Is there an issue with how I'm calling the API? Below is the relevant code:
$(document).ready(function(){
$('#search-submit').click(function() {
getWiki($('#searchVal').val());
});
/*add code for get lucky function*/
});
function getWiki(searchParam) {
$.ajax( {
url: 'http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page='+searchParam+'&callback=?',
dataType: 'json',
type: 'POST',
headers: { 'Api-User-Agent': 'Example/1.0' },
success: function(data) {
var result = data;
pageTitle = result.title;
$(".search-box").html(pageTitle);
}
});
};
Here is the HTML:
<body>
<div class="container">
<div class="col-lg-12 header">
<h1>Search Wiki</h1>
</div>
<div class="row search-box">
<div class="col-lg-10">
<input placeholder=" Search" class="input" type="text" id="searchVal" name="searchVal"/></div>
<div class="col-lg-2"><button type="submit" id="search-submit" name="search-submit" class="btn-default">
<i class="fa fa-search fa-2x"></i>
</button></div>
</div>
<div class="row button-box text-center">
<div class="col-lg-12">
<button type="button" class="btn btn-primary" id="random">I'm Feeling Lucky</button></div>
</div>
</div>
</body>
The returned JSON has a parse property before the result, so it has to be data.parse.title to get the title etc.
$(document).ready(function() {
$('#search-submit').click(function() {
getWiki($('#searchVal').val());
});
/*add code for get lucky function*/
});
function getWiki(searchParam) {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page=' + searchParam + '&callback=?',
dataType: 'json',
type: 'POST',
headers: {
'Api-User-Agent': 'Example/1.0'
},
success: function(data) {
var result = data.parse;
var pageTitle = result.title;
$(".search-box").html('The title is : ' + pageTitle);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Search for something : <input id="searchVal"><button id="search-submit">Search</button>
<br /><br /><br />
<div class="search-box"></div>

Categories

Resources