Save Image Into Database using api - asp.net-mvc

I have a web application with many layers (DAL, BLL, SL, UI), each layer in a separate project.
I am consuming a Web API in the presentation layer (UI) using ajax, where I am using single page application.
Example: in index action in home controller in the presentation layer(UI) only refers to view:
public class MaCityController : Controller
{
public IActionResult Index()
{
return View("~/Views/Mainten/MasterFile/MaCity/Index.cshtml");
}
}
and in this view I am doing my CRUD operation using Web API and Ajax:
function Add() {
var NameAr = $('#NameAr').val();
var NameEn = $('#NameEn').val();
var Image = $('#FileName').val();
var newData = new Object();
newData.NameAr = NameAr;
newData.NameEn = NameEn;
newData.Image=Image;
$.ajax({
type: "POST",
url: APIURL + "api/MaCity/Add",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(newData),
success: function () {
$('#myModal').modal('hide');
debugger;
loadData();
},
failure: function (data) {
alert(data.statusText);
},
error: function (data) {
alert(data.statusText);
}
});
}
}
My posting code in Sl as
[HttpPost]
public IActionResult Add(City scItem)
{
_unitOfWork.GetRepository<City>().Add(scItem);
_unitOfWork.SaveChanges();
return Ok();
}
Where api In another Application with different port than presentation Layer (UI)
and any dealing with database occurs in SL (NO DEAL WITH DATA IN UI).
I need to upload an image to the server and save (image server url) into the database.
I read many articles but I can't find solution to solve my problem.
Any help?

Have you tried checking if the file is getting added to the json request object? there are a few ways you can try this, e.g using a tool like Telerik Fiddler
inside your json post method, check if there are any files in your form
var file =$(this).prop('files')[0];
A somewhat example would be the following
add the image to FormData
formdata = new FormData();
if($(this).prop('files').length > 0)
{
var file =$(this).prop('files')[0];
formdata.append("image", file);
}
Then finally post the post the image
jQuery.ajax({
url: "api_path,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
// if all is well
// play the audio file
}
});
You can also try sending the data from your Controller(assuming you are using some MVC flavour)

Related

Pass array of string from ajax to controller

I need to send an array of string from ajax to a controller and I need to return a file to download. I already look and everywhere says that the same solution, but I can not make it work. I have put a break on the controller, but never entered.
The controllers are in different project.
SOLUTION
PROJECT 1
Controllers
ApiControllers
RenderMvcControllers
SurfaceControllers
ExportController
PROJECT 2
function GetData() {
var stringArray = new Array();
stringArray[0] = "item1";
stringArray[1] = "item2";
stringArray[2] = "item3";
var postData = { values: stringArray };
$.ajax({
type: "POST",
url: "/umbraco/Surface/Export/HandleDownloadFile",
data: postData,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert();
alert(data.Result);
},
error: function (data) {
alert("Error: " + data.responseText);
},
});
}
class ExportController : SurfaceController
{
[HttpPost]
public ActionResult HandleDownloadFile(string[] productList)
{
return CurrentUmbracoPage();
}
}
If you are sending array values via AJAX, you'll need to ensure that the traditional attribute is set to true (which allows this behavior) and that your parameter is named to match what MVC expects that it should be productList :
// This is important for passing arrays
traditional: true,
Secondly, since you are posting this to a different project, you may need to explicitly define where the project is running by using an absolute URL (as a relative one would be used by default and would likely point to your current project) :
url: "{your-other-project-url}/umbraco/Surface/Export/HandleDownloadFile",
Finally, you may want to try removing the contentType attribute as that is used to define what the server expects to receive in it's response. Since you aren't expecting JSON back (and instead are expecting a file), you could consider removing it.
$.ajax({
type: "POST",
// Consider making the URL absolute (as it will be relative by default)
url: "/umbraco/Surface/Export/HandleDownloadFile",
// This is important for passing arrays
traditional: true,
// Make sure that productList is used as it matches what your Controller expects
data: { productList: stringArray }.
dataType: "json",
success: function (data) {
alert(data.Result);
},
error: function (data) {
alert("Error: " + data.responseText);
},
});

Ajax Request issue with ASP.NET MVC 4 Area

Today i discovered something weird, i have regular asp.net mvc 4 project with no such ajax (just post, get). so today i need ajax request, i did an ajax action with jquery in controller and it didn't work out. Here is my code
Areas/Admin/Controllers/BannersController
public JsonResult SaveOrder(string model)
{
bool result = false;
if (!string.IsNullOrEmpty(model))
{
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(model);
result = repository.SaveOrder(list);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
View side (Its in area too)
$(document).ready(function () {
$("#saveOrder").click(function () {
var data = JSON.stringify($("#list_banners").nestable('serialize'));
$.ajax({
url: '#Url.Action("SaveOrder", "Banners", new { area = "Admin" })',
data: { model: data },
success: function (result) {
if (result) {
toastr.success('Kaydedildi.');
}
else {
toastr.error('kaydedilemedi.');
}
},
error: function (e) {
console.log(e);
}
});
});
});
i've already tried everything i know, which is $.post, $.get, ajax options, trying request from out of area etc.. just request can't reach action
and here is the errors ,
http://prntscr.com/297nye
error object
http://prntscr.com/297o3x
Try by specifying the data format (json) you wand to post to server like and Also change the way you pass data object in JSON like this :
var data = $("#list_banners").nestable('serialize');
$.ajax({
url: '#Url.Action("SaveOrder", "Banners", new { area = "Admin" })',
data: JSON.stringify({ model: data }),
dataType: 'json',
contentType: "application/json",
...
I had same issue, but after spending too much time, got solution for that. If your request is going to your specified controller, then check your response. There must be some problem in your response. In my case, response was not properly converted to JSON, then i tried with passing some values of response object from controller using select function, and got what i needed.

Errors when passing data via jquery ajax

I have a pretty simple ajax request that I'm sending over to server in order to get some data and fill up my edit modal. But for some reason it keeps returning with error and I can't figure out why. I've debugged the server side, parameter comes in correctly and all data is properly found and returned, still an error though.
Here's my code so someone might see what am I missing here.
Request:
function EditNorm(id) {
$.ajax({
type: "POST",
url: "#Url.Action("GetNormViewModel")",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({id : id}),
cache: false,
success: function(data) {
FillFormForEditing(data.nvm);
},
error: function() {
alert("Error On EditNorm function");
}
});
}
Server side:
public JsonResult GetNormViewModel(int id)
{
var nvm = new NormViewModel {Norm = db.Norms.Find(id), Materials = db.Materials.ToList()};
return Json(new {nvm = nvm}, JsonRequestBehavior.AllowGet);
}
Firstly: You are using a POST method on your javascript while your controller accepts a Get, add this to your action:
[HttpPost]
public JsonResult GetNormViewModel(int id)
{
return Json(new { ... });
}
Secondly: What is db is it LinqToSQL / Entity Framework context? If so, make sure no call to your data context is performed after the data is returned. (i.e. changed your action and simply return return Json(new { nvm = "test" }); and console.log/alert to make sure you've got the result back. This will tells you that its your model that failed when it's returned due to some late binding.

How to ajax/post JSON array to ASP MVC

Trying to do a post including some JSON data that has an array of integers in it. Pressing the button on my page to perform the post is getting to the action, but the expected data is not there (the two int[] variables are null). Doing a network profile while posting shows that the request body includes data like this:
groups%5B%5D=2&groups%5B%5D=3&alerts%5B%5D=5&alerts%5B%5D=9
Javascript:
$('#modal-save').click(function() {
var selectedGroups = [];
var selectedAlerts = [];
$('input:checked').filter('[data-group="true"]').each(function() {selectedGroups.push($(this).data('id')); });
$('input:checked').filter('[data-group="false"]').each(function() {selectedAlerts.push($(this).data('id')); });
$.ajax({
type:'Post',
dataType: 'json',
url:'#Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},
});
MVC Action:
[HttpPost]
public bool UpdateAlertStores(string alias, Guid? groupID, Guid? storeID, int[] groups, int[] alerts)
{
return true;
}
add traditional:true
traditional: true,
type:'Post',
dataType: 'json',
url:'#Url.Action("UpdateAlertStores", new { alias = ViewBag.Alias})',
data: {groups: selectedGroups, alerts: selectedAlerts},
after this changing your url looks like:
groups=2&groups=3&alerts=5&alerts=9

unable to post the data with bool value in asp.net web api

I am working on asp.net mvc webapi with EF code first with existing database. I have a class like,
public class User
{
public bool IsAgree{get; set;}
}
Iam using MySql database, my table looks like.
--------------
|ID |IsAgree|
--------------
|int |tinyint|
--------------
and i have a post action like
public HttpReponseMessage PostUser(HttpRequestMessage request,User user)
{
// some code to handle user data..
}
and from my view i am trying to post some data to the action like,
$(document).ready(function () {
var sendata = {"IsAgree":true};
$.ajax({
url: '/api/account',
type: 'POST',
data: sendata,
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function (data) {
alert(data.status);
},
error: function (xhr) { alert(xhr.status); }
});
});
when i put breakpoint at action it shows user as null and i get alert message as 400 i.e. bad request. Is my json data was well for my model? Please guide me.
Try to send the data in this way :
data: JSON.stringify({ sendata })

Resources