Umbraco - MediaPicker Object Data to JSON - json

In Umbraco 7, is it possible to serialize a mediapicker to json? So it could be something like this....
[{'name':'muffin', 'file':'muffin.jpg', 'text':'some text', 'etc': 'and so on'}]
My setup is like this, I have a mediaPicker named "mediaPhotos". Contained in the folder selected by the mediaPicker I have images of a custom media type "sillyImage".
I can create a controller and query only single items as xml. What I'm trying to target the entire folder of images chosen by the mediapicker and convert its contents to json.
I'm trying to use the solution posted by bowserm below which works like this...
It gets the CurrentPage dynamically with the mediaPicker alias. Then its passed the custom media type.
public class MediaApiController : UmbracoApiController
{
[HttpGet]
public MediaApiModel GetMediaById(string id)
{
var media = Umbraco.TypedMedia(id);
return new MediaApiModel
{
MediaId = media.Id,
MediaUrl = media.Url
};
}
[HttpGet]
public IEnumerable<MediaApiModel> GetMediaObj(string mediaAlias)
{
var currentPage = Umbraco.TypedContent(UmbracoContext.Current.PageId);
var mediaRootId = currentPage.GetPropertyValue<string>("mediaPhotos");
var mediaRoot = Umbraco.TypedMedia(mediaRootId);
var media = mediaRoot.Children.Where(m => m.IsDocumentType(mediaTypeAlias));
return media.Select(m => new MediaApiModel
{
MediaId = m.Id,
MediaUrl = m.Url
});
}
}
var uri3 = '//' + document.domain + ':14712' + '/umbraco/api/MediaApi/GetMediaFolder?mediaAlias=sillyImage';
$(document).ready(function () {
$.getJSON(uri3)
.done(function (data) {
console.log('return json data object ' + data);
});
});
I'm getting a 500 error now so its getting closer. The issue I think is with these lines in the controller
var currentPage = Umbraco.TypedContent(UmbracoContext.Current.PageId);
var mediaRootId = currentPage.GetPropertyValue<string>("mediaPhotos");
var mediaRoot = Umbraco.TypedMedia(mediaRootId);
My pages use a page name so PageId I'm not sure is the root issue. The one item I know is that the GetPropertyValue isn't able to get the media picker object from the current page.
Thanks!

You should be able to get your Api Controller to automatically serialize the results to JSON. Just inherit from UmbracoApiController.
public class MediaApiController : UmbracoApiController
{
[HttpGet]
public MediaApiModel GetMediaById(string id)
{
var media = Umbraco.TypedMedia(id);
return new MediaApiModel
{
MediaId = media.Id,
MediaUrl = media.Url
};
}
[HttpPost]
public IEnumerable<MediaApiModel> GetMediaObj(string mediaTypeAlias)
{
var currentPage = Umbraco.TypedContent(UmbracoContext.Current.PageId);
var mediaRootId = currentPage.GetPropertyValue<string>("mediaPhotos");
var mediaRoot = Umbraco.TypedMedia(mediaRootId);
var media = mediaRoot.Children.Where(m => m.IsDocumentType(mediaTypeAlias));
return media.Select(m => new MediaApiModel
{
MediaId = m.Id,
MediaUrl = m.Url
});
}

Related

How do I consume a JSon object that has no headers?

My C# MVC5 Razor page returns a Newtonsoft json link object to my controller (the "1" before \nEdit |" indicates that the checkbox is checked:
"{\"0\": [\"6146\",\"Kimball\",\"Jimmy\",\"General Funny Guy\",\"277\",\"Unite\",\"Jun 2019\",\"\",\"\",\"1\",\"\nEdit |\nDetails\n\n \n\"],\"1\": [\"6147\",\"Hawk\",\"Jack\",\"\",\"547\",\"Painters\",\"Jun 2019\",\"\",\"\",\"on\",\"\nEdit |\nDetails\n\n \n\"]}"
How do I parse this?
I am using a WebGrid to view and I want to allow the users to update only the lines they want (by checking the checkbox for that row), but it doesn't include an id for the 's in the dom. I figured out how to pull the values, but not the fieldname: "Last Name" , value: "Smith"... I only have the value and can't seem to parse it... one of my many failed attempts:
public ActoinResult AttMods(string gridData)
{
dynamic parsedArray = JsonConvert.DeserializeObject(gridData);
foreach (var item in parsedArray)
{
string[] itemvalue = item.Split(delimiterChars);
{
var id = itemvalue[0];
}
}
I finally sorted this one out..If there is a more dynamic answer, please share... I'll give it a few days before I accept my own (admittedly clugy) answer.
if(ModelState.IsValid)
{
try
{
Dictionary <string,string[]> log = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string[]>>(gridData);
foreach (KeyValuePair<string,string[]> keyValue in log)
{
if (keyValue.Value[9] == "1")//Update this row based on the checkbox being checked
{
var AttendeeID = keyValue.Value[0];
int intAttendeeID = 0;
if (int.TryParse(AttendeeID, out intAttendeeID))//Make sure the AttendeeID is valid
{
var LName = keyValue.Value[1];
var FName = keyValue.Value[2];
var Title = keyValue.Value[3];
var kOrgID = keyValue.Value[4];
var Org = keyValue.Value[5];
var City = keyValue.Value[7];
var State = keyValue.Value[8];
var LegalApproval = keyValue.Value[9];
tblAttendee att = db.tblAttendees.Find(Convert.ToInt32(AttendeeID));
att.FName = FName;
att.LName = LName;
att.Title = Title;
att.kOrgID = Convert.ToInt32(kOrgID);
att.Organization = Org;
att.City = City;
att.State = State;
att.LegalApprovedAtt = Convert.ToBoolean(LegalApproval);
}
}
}
db.SaveChanges();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
You can avoid assigning the var's and just populate the att object with the KeyValue.Value[n] value, but you get the idea.

mvc controller json return

i want to return an image in base64 from my controller to view using json.
public JsonResult changeProfile()
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
TBL_User item = _context.TBL_User.Find(userID);
UserModel model = new UserModel();
model.UserID = userID;
model.BinaryPhoto = item.BinaryPhoto;
return Json(new
{
??????????????'
},
JsonRequestBehavior.AllowGet);
}
what can i put there to return my image and display in the view?
thanks
Update controller
public JsonResult changeProfile()
{
var userID = ((SessionModel)Session["SessionModel"]).UserID; // get current user id
TBL_User item = _context.TBL_User.Find(userID);
UserModel model = new UserModel();
model.UserID = userID;
model.BinaryPhoto = item.BinaryPhoto;
var base64 = Convert.ToBase64String(model.BinaryPhoto);
var imgsrc = string.Format("data:image/jpg;base64,{0}", base64);
return Json(new
{
Image = imgsrc
},
JsonRequestBehavior.AllowGet);
}
Update src for image in ajax success
$.ajax({
url: "/changeProfile",
success: function(data) {
$(".img-circle").attr('src', data.Image);
}
});

how to pagination JSONResult in MVC with ajax url data loading?

I have a problem in pagination with a json result data in MVC.
Below code is my ajax data loading:
jQuery.ajax({
url: "/Products/Search",
type: "POST",
dataType: "json",
success: function (data) {
displayData(data);
},
error: function (errdata, errdata1, errdata2) { $('#ProductList').html("Error in connect to server" + errdata.responseText); }
and my controller JsonResult is below:
public JsonResult List()
{
tbl = db.tblProducts;
return Json(tbl, JsonRequestBehavior.AllowGet);
}
I can recive data from above ajax data loading successfully, but I can't pagination it.
Please help me.
Thank you.
There is no code for Pagination,Do you want to do client side pagination or server side
Thinking your devloping an ASP.Net MVC application
Server side pagnation : You can load the specific number of records alone.
Using Skip and Take functionlitys
public JsonResult GetOrders(int pagesize, int pagenum)
{
var query = Request.QueryString;
var dbResult = db.Database.SqlQuery<Order>(this.BuildQuery(query));
var orders = from order in dbResult
select new Order
{
ShippedDate = order.ShippedDate,
ShipName = order.ShipName,
ShipAddress = order.ShipAddress,
ShipCity = order.ShipCity,
ShipCountry = order.ShipCountry
};
var total = dbResult.Count();
orders = orders.Skip(pagesize * pagenum).Take(pagesize);
var result = new
{
TotalRows = total,
Rows = orders
};
return Json(result, JsonRequestBehavior.AllowGet);
}
Client side pagination : Load the entire records to your view from there implement pagination
Sample code : http://jsfiddle.net/rniemeyer/5xr2x/
Database db = new Database();
public int PageSize = 5;
public int VisiblePageCount = 5;
public JsonResult Search(int page = 1)
{
var model = new ModelName();
var tbl = db.tblProducts;
var renderedScheduleItems =(tbl.Skip((page - 1) * PageSize)
.Take(PageSize)
.ToList());
model.Products = renderedScheduleItems;
model.PagingDetail = new PagingDetail()
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = items.Count,
VisiblePageCount = VisiblePageCount
};
return Json(model, JsonRequestBehavior.AllowGet);
}

View gets Json displayed on the page. not the data

I have an action which returns a JsonResult. The only thing gets displayed on the view is my json which is like
ProcessOrder{"IsValid":true,"url":"/Home/ProcessOrder"}
While debugging the code, I noticed that it gets displayed because of this below line.
var ProcessOrderData = new { IsValid = true, url = Url.Action("ProcessOrder") };
return new JsonResult() { Data = ProcessOrderData };
Can any body please tell me why it gets only json to be displayed on the view?
is something null here that is causing this to get this displayed or any other stuff?
Code:
private ActionResult SubmitAccount(UserAccountModels UserAccountModels)
{
SessionInfo userSession = SiteSetting.Visitor;
if (userSession != null)
{
if (userSession.products.Where(rec => rec.IsAddedToCart).Count() > 0)
{
SiteSetting.Visitor.User.FirstName = UserAccountModels.FirstName;
SiteSetting.Visitor.User.LastName = UserAccountModels.LastName;
SiteSetting.Visitor.User.Phone = UserAccountModels.Phone;
SiteSetting.Visitor.User.Email = UserAccountModels.Email;
var ProcessOrderData = new { IsValid = true, url = Url.Action("ProcessOrder") };
return new JsonResult() { Data = ProcessOrderData };
}}}
It will only display Json because you are returing JsonResult not a View

Encompassing object attributes with HTML and return in JSON

currently, i have written the following json search method.
[HttpPost]
public JsonResult Search(string videoTitle)
{
var auth = new Authentication() { Email = "abc#smu.abc", Password = "abc" };
var videoList = server.Search(auth, videoTitle);
String html = "";
foreach(var item in videoList){
var video = (Video)item;
html += "<b>"+video.Title+"</b>";
}
return Json(html, JsonRequestBehavior.AllowGet);
}
On screen, it returns this.
"\u003cb\u003eAge of Conan\u003c/b\u003e"
what should i do? The reason why i want to do this is so that i can make use of CSS to style tags so that it looks aesthetically better as the items drop down from the search input.
thanks
If you want to return pure HTML you shouldn't return JSON, you should rather use the ContentResult:
[HttpPost]
public ContentResult Search(string videoTitle)
{
var auth = new Authentication() { Email = "smu#smu.com", Password = "test" };
var videoList = server.Search(auth, videoTitle);
String html = "";
foreach(var item in videoList)
{
var video = (Video)item;
html += "<b>"+video.Title+"</b>";
}
return Content(html, "text/html");
}
You can request that with standard jQuery.get() and insert directly into DOM.