How can I send my files from my javascript(files are through react dropzone) to my asp.net core api?
I am using axios and I have something like this
var data = new FormData();
data.append('folderName', "4141515");
data.append('file', files[0].fileObject); //dropzone wraps the fileobject
axiosInstance2.post("/inventories/ImportImage", data)
[HttpPost("ImportImage")]
public async Task<IActionResult> ImportImage(IFormFile file, string folderName){}
This does work but only the "file" is populated, "foldername" variable is empty.
I tried to put it in a model but it did not work (400 status code)
public class Test
{
public IFormFile file { get; set; }
public string folderName { get; set; }
}
Also is FormData the only way to send it to the server?
Edit
Seems like I need to use [FromForm] Test test
With the .net core api controller, you have to use the [FromBody] tag before the parameter, and change the parameter to type Test, it will bind the values to a class that you can use. Like this:
public async Task ImportImage([FromBody] Test your_values_here){}
Related
Is it possible to send a javascript variable to a controller endpoint, and then have the controller return a new view?
I've tried using a requestbody and ajax to do it, which passes the variable correctly, but is unable to load a new view.
Maybe there's a way to do it with thymeleaf?
If you're using Thymeleaf then just reference the template you want to return to the user by its filename.
#Controller
public class YourController {
#GetMapping("/someUrl")
public String getTemplate(#RequestParam String templateName){
return templateName;
}
}
This would be the bare minimum that you'd need, assuming your templates are in the correct folder - by default in resources/static. If the frontend sends a GET (/someUrl?templateName=xyz) to the backend, it would return the xyz.html from your templates. If it does not find the template that was requested in the parameters then it will return a 404.
Edit: Reading through the comments I realized there might be a confusion between #RequestParam and #PathVariable. In case you want to use a path variable to define the template name, so that the frontend can call GET (/someUrl/xyz), then you can do
#Controller
public class YourController {
#GetMapping("/someUrl/{templateName}")
public String getTemplate(#PathVariable String templateName){
return templateName;
}
}
Resources for both below:
https://www.baeldung.com/spring-request-param
https://www.baeldung.com/spring-pathvariable
I am trying to pass dynamic parameters from jquery to mvc controller. This is my jquery function
function OpenBrowserUrl(type, params)
{
window.open("{0}?linkType={1}&{2}".format(URL.openBrowserLinkURL, type, $.param(params)), '_blank');
}
params would be different things based on who passes it in. For example, it's an object like this: var param = { P1: "Test1", P2: "Test2" }
I am trying to bind those in MVC Controller. This is what it looks like right now:
public virtual RedirectResult OpenBrowserLink(object urlParameters)
{
IDictionary<string, object> paramsPair = new RouteValueDictionary(urlParameters);
foreach (var item in paramsPair)
{
System.Diagnostics.Debug.WriteLine(item.Key);
}
}
However, it's not binding properly. the values are empty. On fiddler, this is how it's sending data: http://www.url.com?param1=1¶m2=2¶m3=3
Any idea what's going on? or Is there a better way to handle this? Basically I am trying to mimic the way Html Helpers send parameters and bind it from the controller side using JQuery. HtmlHelper example: Html.TextboxFor(m => m.Text, new { Param1=1, Param2=2, Param3=3 });
Thanks a lot for the help
Model binder won't work because your object urlParameters has no properties. You should either create strongly typed model:
public class UrlParamerters
{
public string Param1 {get; set;}
public string Param2 {get; set;}
public string Param3 {get; set;}
}
or change your action signature:
public virtual RedirectResult OpenBrowserLink(string[] params)
and just pass an array or parameters.
I must do an upload of some images with Angularjs... The upload must be done in a custom folder, depending on the client is doing the upload... The folder could not exists, so, if it does not, I must create it...
I am doing the upload using this module ...
Here the controller that receive the file:
[HttpPost]
public IHttpActionResult UploadFile()
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
...
return Ok();
}
It works, but I cannot pass parameters to the method.. or perhaps I am not able... I would like something like:
[HttpPost]
public IHttpActionResult UploadFile(MyModel parameters)
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
...
return Ok();
}
Where MyModel, for example, is something like:
public class MyModel
{
public string folderName ....;
...
public List<File> FilesToUpload ...;
}
Perhaps the module I am using is complicating my life, so I can remove it with no problem... Do you have any suggestion?
Thank you
Please refer to following link for detailed information uploading file and sending json data in a single call
"http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/"
I am using a userControl in MVC 4 that has a telerik radeditor.
I want to submit the content of the radeditor the the action method but if I user editor.get_html() the code doesn't execute.
the javascript call to the action method is the following:
function Save() {
var editor = $find("<%=radEdit.ClientID%>");
var editorHtmlContent = editor.get_html();
var entityId = document.getElementById('hdEntityId').value;
var url = '<%=Url.Action("SaveNote", "staticController")%>';
$.post(url, { EntityId: entityId, Desc: editorHtmlContent }, function (result) { });
}
any clue?
Posting HTML tags is being considered a security threat (HTML Injection and Cross-site Scripting (XSS)), so it is blocked by default. You have three ways out of this:
Encode your HTML on client side before sending to the server. You can find a lot of reading about that on SO, for example here: Fastest method to escape HTML tags as HTML entities?
If you have strongly typed model class and want to get the actual HTML, you can use AllowHtmlAttribute:
public class XMLModel
{
public int EntityId { get; set; }
[AllowHtml]
public string Desc { get; set; }
}
Last option is to disable input validation for entire action, which can be done with ValidateInputAttribute:
[ValidateInput(false)]
[HttpPost]
public ActionResult SaveNote(...)
{
...
}
You should choose the option most suitable for you.
I am using an activex control to get images from a hardware device (front and back). These images are created as a VBArray.
data = {
FrontImageData: scanResult.MemoryScanResult.FrontImageTiff.toArray(),
BackImageData: scanResult.MemoryScanResult.BackImageTiff.toArray(),
};
This puts the VBArray into an array in my json object.
It's your standard binary/integer array. I am doing an ajax post to my server, which works fine. The problem is on the backend.
[Authorize]
[HttpPost]
public JsonResult SubmitItem(SubmitItemRequest request)
{
return Json(null);
}
And my model. There is other data that I am passing in through my ajax post, but it isn't important.
public class SubmitCheckRequest
{
public byte[] FrontImageData { get; set; }
public byte[] BackImageData { get; set; }
}
My problem is that my front and back images are coming to the server as null. When I evaluate the Request, the data is there, but MVC is not translating the data correctly into my model.
Maybe the problem is how the 'VBArray' is being translated into the array? Any ideas how to get the binary data to the server so I can save the images along with the meta data?