I'm using FormData to upload files. I also want to send an array of other data.
When I send just the image, it works fine. When I append some text to the formdata, it works fine. When I try to attach the 'ProIList' array below, everything else works fine but no array is sent
this is my angular.js file code :
this.AddPro = function (file, P) {
var formData = new FormData();
formData.append("file", file);
formData.append("name", P.name);
formData.append("description", P.description);
formData.append("ProIList", P.ProIList); // this is array list
var Response = $http.post("/Product/AddProduct", formData,
{
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function (res) {
Response = res;
})
.error(function () {
});
return Response;
}
this is my controller method :
[HttpPost]
[Route("AddProduct")]
public string AddProduct(string name, string description, IList<ProductItems> ProIList) // here i m not getting array
{
Products objP = new Products();
string Res = "";
objP.name = name;
objP.description = description;
db.Promotions.Add(objP); // and here add product is done now want to add ProductItems table entry so how can do
db.SaveChanges();
return Res;
}
this is my entity productItmes :
[Table("ProductItems ")]
public class ProductItems
{
[Key]
public int id { get; set; }
[ForeignKey("Products")]
public int pid {get; set;}
public int Qty { get; set; }
public Decimal Rate { get; set; }
public virtual Products Products { get; set; }
}
Related
I am passing a json data using jQuery to a Ajax call. I want to read this json in my Application_BeginRequest function on global.ascx for some puspose.
Where can i find this data in "Request" object.
I found that the Questystring and the Form of Request object. both are empty.
Calling ajax function as below using jQuery
Regards
Umesh
var inputData = "{'ID':'" + ID + "', 'Code':'" + Centre +"'}";
var pageURL = window.location.protocol + "//" + window.location.host +
"/webmethod.aspx/MyFunction"
$.ajax({
type: "POST",
url: pageURL,
data: inputData,
contentType: "application/json; charset=utf-8",
dataType: "json",
P.S - Assuming you want to post the json data using **jquery** to your ASPX page, Adding a sample below.
function GetEmployee()
{
var jsonObj = {"Org":0 ,"Dept":0,"Desg":0,"Grp":0,"SubGrp":0,"Loc":0,"Prv":'CanViewEmployee',"CustAttrId":0,CustAttrVal:"","Status":'1' };
$.ajax({
url: 'EmployeeSearchControl.aspx/populateJsonResult',
datatype: 'json',
data:JSON.stringify(jsonObj),
method: 'Post',
success: function (data) {
if(data != null || data != "")
{
for(var i=0;i<data.length;i++)
{
addEmployeeToGrid(data[i]);
}
}
}
})
}
public class JSONRequest
{
public long Org { get; set; }
public long Dept { get; set; }
public long Desg{ get; set; }
public long Grp { get; set; }
public long SubGrp { get; set; }
public long Loc { get; set; }
public long Cat { get; set; }
public string Prv { get; set; }
public long CustAttrId { get; set; }
public string CustAttrVal { get; set; }
public string Status { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/json";
string ap = Request["org"];
HttpContext.Current.Request.InputStream.Position = 0;
string jsonString = "";
using (StreamReader inputStream = new StreamReader(this.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
}
JSONRequest masterDetails = Newtonsoft.Json.JsonConvert.DeserializeObject<JSONRequest>(jsonString);
}
Hope it helps. Please let me know if you require any other help.
I am posting form data to webAPI and one of object has boolean value(i.e from checkbox; Deviceselected has boolean values here in code).this object returns null in my api controller.
I tried declaring Desktop and Mobile as string in controller.That did not fix as well.
What am i missing in here?
I'm able to post other data except Deviceselected
Angualrjs controller code
$scope.SendData = function (Data) {
var GetAll = new Object();
GetAll.Redirection = Data.redirection;
GetAll.Deviceselected = new Object();
GetAll.Deviceselected.Desktop = Data.devSelected.desktop;
GetAll.Deviceselected.Mobile = Data.devSelected.mobile;
GetAll.Protocol = Data.protocol;
$http({
url: "http://localhost:61352/api/Market",
dataType: 'json',
method: 'POST',
data: GetAll,
headers: {
"Content-Type": "application/json"
}
}).then(successCallback, errorCallback);
};
})
Web API code
public class SubmitData
{
public string Redirection { get; set; }
public Deviceselected deviceSelected;
public string Protocol { get; set; }
}
public class Deviceselected
{
public Boolean Desktop { get; set; }
public Boolean Mobile { get; set; }
}
[HttpPost]
public string sendData(HttpRequestMessage request,[FromBody] SubmitData marketModel)
{
return "Data Reached";
}
Apparently it works with the same logic.1)Cleared cache 2)Run API and then load HTML
Its already asked question. But still i didnt clear.
I have to call POST Method of WEBAPI in reactjs. But i have created model in webapi. So i want to know how to pass the model data to post call in reactjs.
Model :
public class EmployeeModels
{
public int Id { get; set; }
public string name { get; set; }
public string mobile { get; set; }
public string email { get; set; }
public string dept { get; set; }
public string erole { get; set; }
}
My WEBAPI Post Method :
//Insert new Employee
public IHttpActionResult CreateNewEmployee(EmployeeModels emp)
{
using (var ctx = new Employee())
{
ctx.tempemp.Add(new tempemp()
{
Id = emp.Id,
name = emp.name,
mobile = emp.mobile,
erole = emp.erole,
dept = emp.dept,
email = emp.email
});
ctx.SaveChanges();
}
return Ok();
}
Now i should want to post Employeemodel from reactjs. Kindly give any suggestions.
I have already given answer:
let employee={
Id:1,
name:'abc',
mobile:123456,
email:'abc#abc.com',
dept:'IT',
role:'Developer'
}
fetch('https://mywebsite.com/CreateNewEmployee/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(employee)
})
.then(function(resp){
// your response
})
You can use axios library.
npm install axios --save
and then:
axios.post('/CreateNewEmployee/', {
Id:1,
name:'abc',
mobile:123456,
email:'abc#abc.com',
dept:'IT',
role:'Developer'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I wanna achieve a simple task, which is to retrieve the binary image, and display it in my html
public class Artwork
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid artworkID { get; set; }
public string artworkName { get; set; }
public string artworkMimeType { get; set; }
public byte[] artworkMeta { get; set; }
public string artworkBase64String { get; set; }
}
Gets the artwork from DB
public Artwork GetArtwork(Guid id)
{
return _context.Artworks.SingleOrDefault(a => a.artworkID == id);
}
The API Controller
public IHttpActionResult Get(Guid id)
{
if (id == null)
{
return BadRequest();
}
var artwork = _repository.GetArtwork(id);
if (artwork == null)
return NotFound();
else
return Ok(artwork);
}
I've also used this method and it returns the data I want, but I still don't know how to use it to achieve my goal.
[HttpGet]
public HttpResponseMessage Get(Guid id)
{
HttpResponseMessage result = null;
try
{
var artwork = _repository.GetArtwork(id);
if (artwork == null)
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
// sendo file to client
byte[] bytes = artwork.artworkMeta ;
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(bytes);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = artwork.artworkName;
}
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
}
And here's my angular request
$scope.getCity = function (id) {
$http.get('/api/artwork/' + $RouteParams.id).success(function (response) {
$scope.artwork= response;
//I've seen dudes using Blob here, but I'm not sure how that works
});
}
My problem is my angular request and my html, how do I display the artwork without doing this:
<img ng-src="data:{{artwork.artworkartworkMimeType}};base64,{{artwork.artworkBase64String}}" class="img-responsive" />
This displays the image, but I don't like how clumsy it looks, and I'm gonna be working with audio files as well, so I need a clean and understandable way. Please help!
As you said, this can be done by using a blob.
First step is to set the content type to application/octet-stream in the api method
[HttpGet]
public HttpResponseMessage Get(Guid id)
{
HttpResponseMessage result = null;
try
{
var artwork = _repository.GetArtwork(id);
if (artwork == null)
{
result = Request.CreateResponse(HttpStatusCode.Gone);
}
else
{
// sendo file to client
byte[] bytes = artwork.artworkMeta ;
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new ByteArrayContent(bytes);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = artwork.artworkName;
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
return result;
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.Gone);
}
}
Then add the client request where you create a blob from the response. An url is then created for the blob which will be the source for the img
$scope.fileURL = '';
$http({
method: 'GET',
url: '/api/artwork/' + $RouteParams.id,
responseType: 'arraybuffer',
headers: {
'Access-Control-Allow-Origin': '*',
}
}).success(function (data, status, headers) {
headers = headers();
var contentType = headers['content-type'];
var blob = new Blob([data], { type: contentType });
//Create a url to the blob
$scope.fileURL = window.URL.createObjectURL(blob);
}).error(function (message) {
console.log(message);
});
Then bind url to the ngSrc
<img ng-src="{{fileURL}}" class="img-responsive" />
You could store image in binary format without encoding it to base64. Then it would be simpler to retrive image from DB.
In your asp controller:
[HttpGet]
public FileResult GetPhoto(int id) {
return File(_repository.GetArtwork(id).artworkMeta, "image/jpg");
}
And in angular view:
<img ng-src="/Home/GetPhoto/2" />
Similar questions have been asked so many times, but there are no clear answers, I still have trouble getting mine to work.
This is the model in C#
public class SubmitModel
{
public string Name { get; set; }
public HttpPostedFileBase File { get; set; }
public IEnumerable<HttpPostedFileBase> Files { get; set; }
}
This is the MVC code
[HttpPost]
public ActionResult Test(SubmitModel model)
{
// Here model.File and model.Files is always null
}
This is what I submitted using AngularJS
var data = {
name: scope.name, // This is passed to MVC successfully
file: scope.files[0], // Doesn't even work with single file
files: scope.files // This is a FileList
};
$http.post("/umbraco/surface/MyController/Test", data).success(...);
If you want to know how I assign scope.files:
$('#upload').on('change', function (e) {
scope.$apply(function () {
scope.files = e.target.files;
});
});
Could someone see what I am missing?
Solved it!
This is how it should be submitted
var data = new FormData();
angular.forEach(scope.item, function (value, key) {
if (key == "files") {
for (var i = 0; i < value.length; i++) {
data.append(value[i].name, value[i]); // Filename:File
}
} else {
data.append(key, value);
}
});
$http.post("/umbraco/surface/MyController/Test", data, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(...);
Then in MVC, we get the files from Request.Files, it won't be in the model.
[HttpPost]
public ActionResult Test(SubmitModel model)
{
var files = Request.Files; // a collection of HttpPostedFileBase
Save(model, files);
}
More info:
https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs
http://www.codeproject.com/Tips/878730/File-Upload-Using-AngularJS-and-ASP-NET-MVC