mvc controller json return - json

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

Related

Asp.Net core Web API: how can I export and import JSON from the external REST APIs?

ASP.Net Core WebAPI is being built to fetch JSON from external REST API endpoint. I would like to save the JSON and reload it
At present, I am fetching the JSON from an external REST API endpoint using the following code:
public async Task<List<Weather>> Get(string cities)
{
List<Weather> weathers = new List<Weather>();
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
foreach (var city in cities.Split(";"))
{
string APIURL = $"?key={this.apiKey}&q={city}";
var response = await _httpClient.GetAsync(APIURL);
if (response.IsSuccessStatusCode)
{
var responses = await response.Content.ReadAsStreamAsync();
var weather = await JsonSerializer.DeserializeAsync<Weather>(responses, options);
weathers.Add(weather);
}
}
return weathers;
}
that returns the following JSON
[
{
"location":{
"name":"Chennai",
"region":"Tamil Nadu",
...
},
"current":{
"last_updated_epoch":1663601400,
"last_updated":"2022-09-19 21:00",
...
}
},
{
"location":{
"name":"Mumbai",
"region":"Maharashtra",
..
},
"current":{
"last_updated_epoch":1663602300,
"last_updated":"2022-09-19 21:15",
..
}
}
]
How can I export and import JSON ?
Update: I have updated the code as mentioned below
public static class JsonFileUtils
{
private static readonly JsonSerializerSettings _options
= new() { NullValueHandling = NullValueHandling.Ignore };
public static void StreamWrite(object obj, string fileName)
{
using var streamWriter = File.CreateText(fileName);
using var jsonWriter = new JsonTextWriter(streamWriter);
JsonSerializer.CreateDefault(_options).Serialize(jsonWriter, obj);
}
public static async Task StreamWriteAsync(object obj, string fileName)
{
await Task.Run(() => StreamWrite(obj, fileName));
}
}
and used it like
public async Task<List<Weather>> Get(string cities)
{
List<Weather> weathers = new List<Weather>();
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
foreach (var city in cities.Split(";"))
{
string APIURL = $"?key={this.apiKey}&q={city}";
var response = await _httpClient.GetAsync(APIURL);
if (response.IsSuccessStatusCode)
{
var responses = await response.Content.ReadAsStreamAsync();
var weather = await JsonSerializer.DeserializeAsync<Weather>(responses, options);
weathers.Add(weather);
}
}
var fileName = "weathers.json";
await JsonFileUtils.StreamWriteAsync(weathers, fileName);
return weathers;
}
to upload the file
[HttpPost("upload", Name = "upload")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(List<Weather>))]
[ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
public async Task<IActionResult> UploadFile(
IFormFile file,
CancellationToken cancellationToken)
{
string fileContent = null;
using (var reader = new StreamReader(file.OpenReadStream()))
{
fileContent = reader.ReadToEnd();
}
var result = JsonConvert.DeserializeObject<List<Weather>>(fileContent);
return Ok(result);
}

.net mvc linq jsonresult

Please look at the Code: how do i split the m.Division ("Divone,a") as object like ["DivOne","a"]
public JsonResult GetData()
{
var series = (from m in db.Fields.AsEnumerable()
where m.tstatus == true
select new
{
name = m.Name,
data = new [] { m.Division }
}).ToArray();
return Json(series, JsonRequestBehavior.AllowGet);
}
The Result
[{"name":"fff","data":["DivOne,a"]},{"name":"a","data":["a"]}]
I want the result Like
[{"name":"fff","data":["DivOne","a"]},{"name":"a","data":["a"]}]
image here:
enter image description here
Change m.Division to m.Division.Split(',')
public JsonResult GetData()
{
var series = (from m in db.Fields.AsEnumerable()
where m.tstatus == true
select new
{
name = m.Name,
data = new[] { m.Division.Split(',') }
}).ToArray();
return Json(series, JsonRequestBehavior.AllowGet);
}
#Sajid
Thank you.... that is a result i wanted
public JsonResult GetData()
{
var series = (from m in db.Fields.AsEnumerable()
where m.tstatus == true
select new
{
name = m.Name,
data = m.Division.Split(',')
}).ToArray();
return Json(series, JsonRequestBehavior.AllowGet);
}
[{"name":"fff","data":["DivOne","a"]},{"name":"a","data":["a"]}]
just use Split(',') for division shown in below.
public JsonResult GetData()
{
var series = (from m in db.Fields.AsEnumerable()
where m.tstatus == true
select new
{
name = m.Name,
data = m.Division.Split(',')
}).ToArray();
return Json(series, JsonRequestBehavior.AllowGet);
}

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

Umbraco - MediaPicker Object Data to 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
});
}

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