ASP.Net MVC Web API JavaScriptSerializer - Byte Array - javascript

I have a Web API that is returning some info along with a image (byte array)
var result = response.Result.Content.ReadAsStringAsync();
Snippet:
{"CompanyName":"MyCompany","Address":"Address1","Logo":"iVBORw0KGgoAAAANSUhEUgAAAKAAAABQCAYAAACeXX40AAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAAW6gAAFuoB5Y5DEAAAABx0RVh0U29mdHdhcmUAQWRvYmUgRmlyZXdvcmtzIENTNui8sowAAAAWdEVYdENyZWF0aW9uIFRpbWUAMDcvMjUvMTZmHO7IAAAB6HByVld4nO2WYVKDMBCFowkl3MIreBOv4A/xb6/DZTyAw128gUjFNsmyCRuglDrvSwdtl83blw1MPr8/vtRRHbuua9v+0zZN1zT9taeu67auT38UAAAAAAAAAAAAAABgIbbaaET0t5Kv4H+X/vvITf27Oyz5d8Xvaf9sCZcf1vq+0/5vJX9f/q3RJwz/bBTlb9iUEaliSC4Pcv/uchqD+lABU5yLliTi1U7Lj+tTAR1CouVjEKXZVo/CEv/eMOEMugjWpiRRWh4NZ/efTuDP0X8extG4ez9Z6p/RT1c3ET7vIKF/TkAn5XW6Op3WD+ULXt8kqyvSxRfT6z/hwD2FfHgiO8M/78Ap8NGJ7Jz+R/QX+c/Z/zv1/xe9Qv/J65e+/AbS+9+k/RvJ+qensEmDsmRJ/y37BvUecFahSodtTv/tIT5DrD8T26fK2f+cB+OHx8Wlsy8nBKH/8+lFLECyo4sj9e8fYDR3ADLs9Pwm9NJS+lRDfP4anfaDAs1dnf/ZlVhv7N7/lUe+f3e5on+JhLtHUlLknin/c91K88T9l003lh3nBfdg/8/3Hyzkuv7zpl5Qhtz/Urd8/oz+x8vwJYTlbr3/aVkRfQAAAAAAAAAAAAAAAAAA/C9e1Kt6V2/qST3fuhRwA34ABnmlFTLkCiwAAABIbWtCRvreyv4AAAAEAAAAAAAAAAAAAAAAA="}
So when I try to map
var profile = new JavaScriptSerializer().Deserialize<WebApi.Common.DomainObjects.WebProfile>(result);
public class WebProfile
{
public string CompanyName { get; set; }
public string Address { get; set; }
public byte[] Logo { get; set; }
}
I get this error:
Cannot convert object of type 'System.String' to type 'System.Byte[]'
If anyone could provide an example of how to resolve would be great.

Thanks Frank, I ended up Just creating a new property.
public byte[] Logo
{
get { return Convert.FromBase64String(LogoString); }
}
public string LogoString { get; set; }

Related

How to update my data table with POST values. ASP.NET

I want to update values ​​in my database. to make sure my script was working and to send the values ​​I created a POST method to check and the values ​​are coming.
My question now is with the values ​​coming to the method, how to update or save my values ​​in the database?
Controller:
[HttpPost]
public JsonResult EditPost(Programa_Cor_Info_Status statusData)
{
Programa_Cor_Info_Status status = new Programa_Cor_Info_Status
{
ID_Info = statusData.ID_Info,
Status = statusData.Status,
Obs = statusData.Obs,
};
return Json(status, JsonRequestBehavior.AllowGet);
}
I tried using db.savechanges on my controller but to no avail.
Could someone help me with an example?
Thanks
------------Update-----------------------------------------
[HttpPost]
public ActionResult EditPost(Programa_Cor_Info_Status statusData, int ID_Status)
{
Programa_Cor_Info_Status status = new Programa_Cor_Info_Status
{
ID_Info = statusData.ID_Info,
Status = statusData.Status,
Obs = statusData.Obs,
};
var q = db.Programa_Cor_Info_Status.Where(m => m.ID_Info == ID_Status).FirstOrDefault();
q.ID_Info = ID_Status;
db.Entry(q).State = EntityState.Modified;
db.SaveChanges();
return Json(status, JsonRequestBehavior.AllowGet);
}
namespace Balu0._1.Models
{
using System;
using System.Collections.Generic;
public partial class Programa_Cor_Info_Status
{
public int ID_Info { get; set; }
public int ID_Programa { get; set; }
public int ID_Linha_Cor { get; set; }
public string Status { get; set; }
public string Obs { get; set; }
}
}
If you stll don't have, in your view add hidden model field with ID_Info value.
Change your action to this:
public ActionResult EditPost(Programa_Cor_Info_Status statusData)
{
var existItem = db.Programa_Cor_Info_Status.Find(statusData.ID_Info);
// or if you dont have a proper primary key you can try
var existItem = db.Programa_Cor_Info_Status
.Where( i=> i.ID_Info== statusData.ID_Info).FirstOrDefault();
if (existItem != null)
{
db.Entry(existItem).CurrentValues.SetValues(statusData);
var result = db.SaveChanges(); // if result==0 then error
} else ...error
return Json(statusData, JsonRequestBehavior.AllowGet);
}
thanks for the help i already got !!!
db.Entry(status).State = EntityState.Modified;
db.SaveChanges();
return Json(status, JsonRequestBehavior.AllowGet);

Passing complex javascript object to controller. List of objects are always 0

I have a object that I am trying to pass to my C# controller. All the properties get populated except the list I have is always count =0. I have tried setting the header to content-type/json and Json.stringify. Also for testing I am returning the product list from another call so I know that returns a list of products to my view that is formatted correctly.
example for creating request
var request =
'Id':null,
...
... rest of data is here standard properites
...
'Products':productlist
for product list I am currently using the return value from a call that returns a List
return $http.post('api/Enty/Save', request )
.error(function (data, status, headers, config) {
errorLog('error: ' + data);
});
public class Person:IPerson
{
[Required]
public int Id { get; set; }
[MaxLength(90)]
public String Address1 { get; set; }
[MaxLength(90)]
public String Address2 { get; set; }
[MaxLength(40)]
public String Address3 { get; set; }
[MaxLength(40)]
public String City { get; set; }
[MaxLength(2)]
public String State { get; set; }
[MaxLength(40)]
public String Province { get; set; }
[MaxLength(10)]
public String Zip { get; set; }
public IList<IProduct> Products { get; set; }
}
[HttpPost()]
public Response Save(person r)
{}
UPDATE
If I make it List instead of IList it works. Any ideas why?
Turns out the issue was not the Ilist but the Iproduct. I just changed to a concrete class for that property

JavaScript function does not fire when using child model data

I am working on displaying data in a separate div and when I pass my javascript function data it does not fire onclick. It works when I use data from the parent but not after I cast the data from the parent into a child and try to pass the JS function with that data.
##view##
#using WebApplication2.Models
#model IEnumerable<WebApplication2.Models.OBJECT>
#{
ViewBag.Title = "CompAndMon";
}
<script>
//this function does not fire when called
function setO(OfficeLocation,Name,Email,Phone,NumComputers,NumMonitors) {
var text = "Primary Contact Name " + Name+"\n Primary Contact Email: " +Email +"\n Primary Contact Phone: " +Phone +"\n Number of Computers: " +NumComputers +"\n Number Of Monitors: " +NumMonitors;
var location = "Office Location: " + OfficeLocation;
document.getElementById("Nametag").innerHTML = location;
return document.getElementById("OCM").innerHTML = text;
}
//this function does not fire when called
function setComputer(lastS) {
var text = "you selected Item No: " + lastS;
return document.getElementById("OCM").innerHTML = text;
}
//this function operates correctly
function setMonitor(id) {
var text = "you selected Item No: " + id;
return document.getElementById("OCM").innerHTML = text;
}
</script>
#foreach (var item in Model)
{
if (#item.Type == 1)
{
var office = item as Office;
var loc = #office.OfficeLocation;
var Name = #office.Name;
var email = #office.Email;
var phone = #office.Phone;
var mons = #office.NumMonitors;
var comps = #office.NumComputers;
<p><a onlick="setO(#loc,#Name,#email,#phone,#comps,#mons)">#office.Name</a></p>
}
else if (#item.Type == 2)
{
var computer = item as Computer;
<p>  <a onclick="setComputer(#computer.LastUser)">#item.Name1</a></p>
}
else
{
var monitor = item as Monitor;
<p>    <a onclick="setMonitor(#item.ID)">#item.Name1</a></p>
}
}
<h2 id="Nametag" style="text-align:center"></h2>
<div id ="OCM"class="row">
Select a computer or monitor and the information about the de will be displayed here.
</div>
and here are the class models that the view uses
##OCM.cs##
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace WebApplication2.Models
{
public abstract class OBJECT
{
public int ID { get; set; }
public int Type { get; set; }
public string Name1 { get; set; }
}
public class Office:OBJECT
{
public string OfficeLocation { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public int NumComputers { get; set; }
public int NumMonitors { get; set; }
}
public class Computer:OBJECT
{
public String LastUser { get; set; }
public String Name { get; set; }
public int NumMonitors { get; set; }
public String TotalHDSpace { get; set; }
public String FreeHDSpace { get; set; }
public int NumUpdates { get; set; }
}
public class Monitor:OBJECT
{
public String Manufacturer { get; set; }
public String ModelID { get; set; }
public String SerialNum { get; set; }
public int HoursON { get; set; }
public String LastTestTime { get; set; }
public String LastTestType { get; set; }
}
}
When I inspect the element chrome it shows that the data is being passed the the function, but it doesn't run so I am not sure what to do. any help would be appreciated
Here shows that the data was passed to the JS functions when I inspect the element
You use string without quote
setComputer('ted') or setComputer(\"ted\") and not setComputer(ted)
this is the same for email and other arguments
I found that I misspelt onclick in the setO() call and needed to pass my razor variables to the javascript function in single quotes.

viewbag object pass to javascript

I m trying to pass a object to view with viewbag and pass it to javascript parameter in the view
But when comes to assign object to script value it looks like string likes its namespace
in controller:
public ACCIDENT_REPORTS getFilledReportWithEntitiesById(int accidentReport_id)
{
ACCIDENT_REPORTS report = new ACCIDENT_REPORTS();
report = context.ACCIDENT_REPORTS.Include("ACCR_ENTITIES").Where(a => a.ID == accidentReport_id).FirstOrDefault();
return report;
}
ViewBag.Report = DatabaseContext.Current.AccidentReportingRepository.getFilledReportWithEntitiesById(id); //its okey, all data in viewbag
in view:
<script>
debugger
var data = '#ViewBag.Report';
</script>
// in debugger value looks like; var data = 'Application.Database.ACCIDENT_REPORTS;
Why it looks like string ? how can I pass contents of viewbag to javascript value
here is my entity object return type:
public partial class ACCIDENT_REPORTS
{
public ACCIDENT_REPORTS()
{
this.ACCR_ENTITIES = new HashSet<ACCR_ENTITIES>();
}
public decimal ID { get; set; }
public decimal FACILITY_ID { get; set; }
public Nullable<System.DateTime> START_DATE { get; set; }
public Nullable<System.DateTime> END_DATE { get; set; }
public string TITLE { get; set; }
public Nullable<decimal> ACCIDENT_TYPE { get; set; }
public Nullable<decimal> REPORTED_UNDER { get; set; }
public Nullable<decimal> SEVESOII_STATUS { get; set; }
public Nullable<decimal> INDUSTRIAL_ACTIVITY { get; set; }
public string REASON_FOR_REPORTING { get; set; }
public string ACCIDENT_DESCRIPTION { get; set; }
public string SITE_DESCRIPTION { get; set; }
public string UNIT_DESCRIPTION { get; set; }
public string CAUSES_OF_ACCIDENT { get; set; }
public string CONSEQUENCES { get; set; }
public string EMERGENCY_RESPONSE { get; set; }
public string LESSONS_LEARNED { get; set; }
public string ACCIDENTS_INVOLVING { get; set; }
public Nullable<decimal> REPORT_STATUS { get; set; }
public virtual ICollection<ACCR_ENTITIES> ACCR_ENTITIES { get; set; }
}
}
What is the type returned by getFilledReportWithEntitiesById()?
Presumably, it's a Application.Database.ACCIDENT. All the view engine does is invoke .ToString() on what it's given. And the default implementation for .ToString() on any reference type (any child of object basically) is to return the type name.
If you want a custom string representation of your type, then that type needs to override .ToString(). For example:
public override string ToString()
{
return string.Format("{0} - {1}", ID, Name);
}
If the object has an ID property and a Name property then its string representation would then be those values separated by a hyphen (with spaces in between). However you want to structure the string representation of your object would be done within this method.
Conversely, if you don't want it to be a string, but want the JavaScript code to use it as an object, then you want to serialize it to JSON. Something like this:
var data = #Json.Encode(ViewBag.Report);
(You might need to tweak that a little bit, I don't have an environment handy to test it. But you get the idea... To use it as an object in JavaScript code it needs to be serialized to a JavaScript object literal.)
this is the real answer
#Html.Raw(Json.Encode(Model.PlaceStatistic.ToArray()))

Use return values only in javascript

I have an action Map in my Controller Address. In the Action Method I get all the addresses like this:
public ActionResult Map()
{
var model = this.UnitOfWork.AddressRepository.Get();
return View(model);
}
My Address Model looks like this:
public class Address
{
public Int32 Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public Decimal Latitude { get; set; }
public Decimal Longitude { get; set; }
public Int32 StreetNumber { get; set; }
public Int32 RegionId { get; set; }
public virtual Region Region { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
Now I would like to use the latitude and the longitude in the javascript part of the page.
How can I do this?
I've tried to the following:
<script>
var model = #Html.Raw(Json.Encode(Model));
// at this stage the model javascript variable represents the JSON encoded
// value of your server side model so that you can access all it's properties:
alert(model.length);
</script>
But I got this error:
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.Address_F9A550E3CE9AB1122FFC2E0A154FBDCAF8648B6FBCF91A81E35459DCA2E075AA'.
Like it says you have a circular reference somewhere in your mode, but you can set the json parser with options to avoid circular references.
Better would be to parse your mode into a separate viewmodel:
var model = this.UnitOfWork.AddressRepository.Get().Select(m => new ViewModel{
Latitude = m.Latitude,
Longitude = m.Longitude,
});
return View(model);
This way you only expose the information to the client that is needed.
If you need only a few parameters you might be better of with something like this:
<script>
var lat = #Model.Latitude;
var lon = #Model.Longitude;
// at this stage the model javascript variable represents the JSON encoded
// value of your server side model so that you can access all it's properties:
alert(lat);
</script>

Categories