Submit VBArray of Binary data to MVC 3 using JSON - javascript

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?

Related

Sending files through Axios to Asp.net Core Api?

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){}

Can I use c# exe in a fashion similar to PHP in ajax calls

I am currently using jquery to send data from javascript to a php file to execute some server side code:
$.ajax({
url: 'myfile.php', //instead of php, can I call a exe (c#) or asp page here?
type: "POST",
data: ({name: Dummy}),
success: function(data){
}
});
I am facing issues in passing values from my javascript to php file, data is dropped at adfs (eso). So I want to know if a c# exe, or an asp page can be called instead of a php and is it advisable, are there any other way of passing values from client end to server side, my website is made of html files and javascript only.
tried passing this aspx page as URL in above code
Url ="mydomain.com/site/default.aspx";
on the aspx page I am reading
string[] keys = Request.Form.AllKeys;
but the aspx page isnt getting executed (like a php does otherwise)
Take a look at this link, ASP.Net have something know as WebAPI which is great for HTTP services and potentially perfect for what you want.
EDIT:
Based on a comment here is a really basic controller with Get and Post verbs
public class DummiesController : ApiController
{
[HttpGet()]
[Route("api/dummies")]
public IHttpActionResult Get()
{
return this.Ok(new[] {new Dummy(), new Dummy()});
}
[HttpGet()]
[Route("api/dummies/{id}")]
public IHttpActionResult GetById(int id)
{
return this.Ok(new Dummy());
}
[HttpPost]
[Route("api/dummies")]
public IHttpActionResult Post(Dummy dummy)
{
int id = 1;
return this.Created($"api/dummies/{id}", dummy);
}
}

In an action method, how can I bind post data to a dynamic object?

I want to do this:
public ActionResult SaveStuff(dynamic vm) {
StoreTheValue(vm.myvalue);
return Content("Saved :)");
}
This doesn't work, MVC doesn't seem to want to create a dynamic object with properties that correspond to the post data of the request.
Now I know that the whole point of properly defined view models is to create strongly typed data structures and have MVC bind data into them, but given that I'm posting data from javascript using ajax it's not strongly typed data anyway, so I don't see that I'm loosing any maintainability by doing this, and it will save me time and effort creating view model classes.
Can anyone help suggest how I can bind post data to a dynamic object, posssibly using a custom model binder?
One possible way to achieve this would be to use a custom model binder, assuming that you are posting Json to the action
public class DynamicBinder : IModelBinder
{
public object BindModel( ControllerContext controllerContext, ModelBindingContext bindingContext )
{
using( var streamReader = new StreamReader( controllerContext.HttpContext.Request.InputStream ) )
{
return JsonConvert.DeserializeObject< dynamic >( streamReader.ReadToEnd() );
}
}
}
then in your action you can tell it, to use the custom binder
public ActionResult SaveStuff([ModelBinder(typeof(DynamicBinder))]dynamic vm) {
StoreTheValue(vm.myvalue);
return Content("Saved :)");
}
then post your json as such :
{
"myvalue":{...}
}
dynamic type and ajax request that you do with javascript is not corresponding.
You always can create your strongly typed object properties on javascript side.
Anyway you can use FormCollection like this:
[HttpPost]
public ActionResult yourAction(FormCollection collection)
{
StoreTheValue(Convert.ToString(collection["myvalue"]));
return Content("Saved :)");
}
But I think it's better to think of a strongly typed way.

Angular $http post to MVC action, parameter is null

So I do this post:
$http.post(Common.blog.save, { blog: blog })
.then(saveBlogComplete)
.catch(function(message) {
});
And I get this in fiddler output:
{"blog":{"title":"Chicken Is Good","content":"#Chicken Is Good\n##Contents\n* Introduction\n* Factfile\n* Analysis\n* Evaluation\n* Conclusion\n###Introduction\n\n###Factfile","dateAuthored":"","userId":""}}
In my action:
[HttpPost]
public JsonResult Save(string blog)
{
var desBlog = JsonConvert.DeserializeObject<BlogDto>(blog);
return this.ExecuteService(() => this.blogService.Save(desBlog));
}
string blog is coming back null.... I'm not sure why this is happening?
I have done the following
Put breakpoint in JavaScript - data is getting populated
Reviewed Fiddler output - the data is the same as JavaScript obj
Put breakpoint in the Action - it's getting called, the HttpContext doesn't have any data about the POST data in it
Your code will work without stringify function, if you change your mvc action parameter from String to Blog:
public class Blog
{
public string Title {get; set;}
public string Content {get; set;}
public DateTime DateAuthored {get; set;}
public long UserId {get; set;}
}
[HttpPost]
public JsonResult Save(Blog blog)
{
This happening because your blog model on server-side doesn't match to the structure of passing parameter from angular.
I just needed to stringify the data!
$http.post(Common.blog.save, { blog: JSON.stringify(blog) })
.then(saveBlogComplete)
.catch(function(message) {
});

can't pass html tags in parameters in $.post()

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.

Categories

Resources