MVC Partial View Not Displaying Image - javascript

I have a Kendo Grid where one of the columns is actually a link to open a pop up to view the image. I'm able to get the image back but I'm unsuccessful so far. Here is what I have so far-
Controller-
public ActionResult OpenImagePopUp(int? id)
{
Help request2 = new Help();
request2.id = id;
var response = apiHelp.GetHelpRecords(request2);
if (response.Error != null)
{
ErrorLogRequest errorReq = new ErrorLogRequest()
{
LogDate = DateTime.Now,
LogMethod = "GetHelpRecords",
LogPage = "Canopy Help",
LogPerson = User.Identity.Name,
LogInfo = response.Error.ErrorCode + " " + response.Error.ErrorMessage + " " + response.Error.ExceptionObject.Message
};
apiErrorLog.InsertErrorLog(errorReq);
}
var helpRecords = response.data.Select(s => new Help()
{
Image = s.Image
}).FirstOrDefault();
var base64string = Convert.ToBase64String(helpRecords.Image);
request2.ImgSrcBase64 = String.Format("data:image/gif;base64,{0}", base64string);
return PartialView("ImagePopUp", request2);
}
My View / Javascript -
<div>
#(Html.Kendo().Window()
.Name("ImagePopUp")
//.LoadContentFrom("OpenPopUpWindow", "BlueButtonView")
.Draggable()
.Actions(actions => actions.Close())
.Modal(true).Visible(false)
.HtmlAttributes(new { style = "margin: 10px" })
.LoadContentFrom("OpenImagePopUp", "Help")
.Draggable()
.Resizable()
.Width(600)
.Actions(actions => actions.Close())
)
</div>
function showImage(e) {
var grid = $("#CanopyHelpGrid").getKendoGrid();
var item = grid.dataItem($(e.target).closest("tr"));
$("#ImagePopUp").data("kendoWindow").open().center(true);
$.ajax({
datatype: "image",
type: "GET",
url: '#Url.Action("OpenImagePopUp", "Help")',
data: { id: item.id },
success: function (data) {
//$("#imgPopUp").attr('src', data);
}
})
}
Then finally my partial view -
#model OSH.Domain.Models.CanopyHelp.Help
<img id="imgPopUp" alt="Image" src='#Model.ImgSrcBase64'>
I tried to convert the array to a base64 string then format it to be the image source but I keep seeing no image.

As Stephen have suggested, adding this to my ajax solved the problem!
$.ajax({
datatype: "html",
type: "GET",
url: '#Url.Action("OpenImagePopUp", "Help")',
data: { id: item.id },
success: function (html) {
$("#ImagePopUp").html(html);
$("#ImagePopUp").data("kendoWindow").open().center(true);
}
})
I also made my controller return html content instead and removed the image tag on my partial view-
public ActionResult OpenImagePopUp(int? id)
{
if (id != null)
{
string html = string.Empty;
Help request2 = new Help();
request2.id = id;
var response = apiHelp.GetHelpRecords(request2);
if (response.Error != null)
{
ErrorLogRequest errorReq = new ErrorLogRequest()
{
LogDate = DateTime.Now,
LogMethod = "GetHelpRecords",
LogPage = "Canopy Help",
LogPerson = User.Identity.Name,
LogInfo = response.Error.ErrorCode + " " + response.Error.ErrorMessage + " " + response.Error.ExceptionObject.Message
};
apiErrorLog.InsertErrorLog(errorReq);
}
var helpRecords = response.data.Select(s => new Help()
{
id = s.id,
Image = s.Image
}).Where(w => w.id == id).FirstOrDefault();
if (helpRecords.Image != null)
{
var base64string = Convert.ToBase64String(helpRecords.Image);
request2.ImgSrcBase64 = string.Format("data:image/gif;base64,{0}", base64string);
html = string.Format("<img id='imgPopUp' src='{0}' alt='Image'/>", request2.ImgSrcBase64);
return Content(html, "text/html");
}
else
{
html = "<h4>This record has no image attached!</h4>";
return Content(html, "text/html");
}
}
else return new EmptyResult();
}

Related

Accessing the Forge Viewer From Two HTML Files

I have been working on a website incorporating the autodesk-forge viewer (more details can be seen on my past questions). I have successfully made many autodesk-forge viewer functions in a standard javascript (.js) file. These functions include displaying the viewer, and isolating to a particular part, when an external button is pressed.
Currently I have a main html/php home page where I have included my javascript file with all my forge functions using <script src="MyForgeFunctions.js"></script>
These functions are accessed through a button, which successfully displays the viewer in the html page. Attached to my main php/html page, another html/php page was added through an iframe html reference (<iframe src="URL.php"></iframe>). My home page displays the main machines we make, while the embedded php/html page displays all the stations within the machine. I have also included the MyForgeFunctions.js inside this second php/html page. Because of the way the website is set up, I need to be able to access the viewer in both web pages. However, when I attempt to access the viewer from the second html page, I get a message that the viewer is undefined. Below is my code from MyForgeFunctions.js.
var ext = '';
var dim = '';
var assemblyname = '';
function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
isolateSelected();
}
}
//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
isolateSelectedPart();
}
}
/*******************************************************************************
*
* AUTODESK FORGE VIEWER CODE (HTTP REQUESTS)
*
*******************************************************************************/
//VARIABLE DECLARATION
var code = '';
var access_token = '';
const hub = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const project ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const folder='xxxxxxxxxxxxxxxxxxxxxxxxx';
const item = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var itemid = '';
var urn = '';
var urn2 = '';
//allow the program to view data from autodesk
function authorize(){
window.location.href = "https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=data:read data:write bucket:read viewables:read bucket:create data:create";
}
//grab the code from the url
function getCode(){
const querystring = window.location.search;
// console.log(querystring);
const urlParams = new URLSearchParams(querystring);
code = urlParams.get('code');
// console.log(code);
}
//call the function to get the code right away, and obtain a token
getCode();
getToken();
//function to obtain access token
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
data:'client_id=dm2VLfnwJ6rYHKPAg7dG6l9yVbBQPGlH&client_secret=HRMpOPusLhsVoIMk&grant_type=authorization_code&code=' + code + '&redirect_uri=http://team/__MachineViewerMV.php',
success:function(response){
// console.log(response);
access_token = response.access_token;
console.log(access_token);
}
})
}
//Grab desired file id from project folder
function getItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/* beforeSend:function(before){
if(access_token !== '' && viewer !==''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
function get2dItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/*beforeSend:function(before){
if(access_token !== '' && viewer !== ''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName2d){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName2d){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
//get version of the file using its id
function getVersion(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/items/' + itemid + '/versions',
headers:{
Authorization:'Bearer ' + access_token
},
success:function(response){
//console.log(response);
urn = btoa(response.data[0].relationships.storage.data.id);
console.log(urn);
translateToSVF();
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn
},
"output": {
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
// console.log(response);
urn2 = response.urn;
console.log(urn2);
checkStatus();
}
})
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + urn2 + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
if (response.progress == 'complete'){
displayViewer();
}
else if (response.progress !== 'complete'){
alert('File Still Uploading, Press the Display Button Again!');
}
}
})
}
//function to get list of viewables\
var guid = '';
function getViewable(){
$.ajax({
method:'GET',
headers:{
Authorization: "Bearer " + access_token
},
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata',
success:function(response){
console.log(response);
guid = response.data.metadata[0].guid;
console.log(guid);
}
})
}
//funciton to get the list of items within a model
function getTree(){
$.ajax({
method: 'GET',
headers:{
Authorization: "Bearer " + access_token
},
url:'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata/' + guid + '/properties',
success:function(response){
console.log(response);
}
})
}
/**********************************************************************************
*
* FUNCTION TO DISPLAY THE VIEWER IN THE HTML PAGE
*
**********************************************************************************/
var viewer;
function displayViewer(){
//var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
console.log(token);
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
// sessionStorage.setItem("viewer", viewer);
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn2;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
console.log(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
//function to hide the viewer
function destroyViewer(){
console.log(viewer);
viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
}
/*****************************************************************************
* FUNCTIONS TO MODIFY THE VIEWER TO ZOOM INTO THE CORRECT PART/ASSEMBLY
*/
function isolateSelected(){
console.log(dim);
console.log(viewer);
viewer.search(dim, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', dim, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
function isolateSelectedPart(){
console.log(namewithoutextension);
viewer.search(namewithoutextension, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
console.log("getSubset, dbIds.length before = " + dbIds.length)
viewer.model.getBulkProperties(dbIds, {
propFilter: [name],
ignoreHidden: true
}, function(data) {
var newDbIds = []
for (var key in data) {
var item = data[key]
// console.log(item.properties);
if (item.properties[0].displayValue === value) {
newDbIds.push(item.dbId)
}
}
console.log("getSubset, dbIds.length after = " + newDbIds.length)
callback(newDbIds)
}, function(error) {})
}
Because of how the webpage is set up, when I needed to use a variable from the second web page in the first, I used sessionStorage.getItem and sessionStorage.setItem. I have also made a simple function as so inside MyForgeFunctions.js:
function checkViewer(){
console.log(viewer);
}
I then included a button in both html pages to execute the function with an onclick event. When the function is run from the first/home html page the following is displayed:
T {globalManager: e, clientContainer: div#forgeViewer, container: div.adsk-viewing-viewer.notouch.dark-theme.quality-text, config: {…}, contextMenu: o, …}. Which is normal for the viewer, but when the function is executed from the second html page, the viewer is undefined. Any help as to why this is happening or any solutions will be greatly appreciated. Cheers!
From the iframe, in order to access the viewer inside the main web page, I had to use (parent.viewer).

Passing javascript values through html.actionlink

I am developing an export function where I need to pass some values available in javascript code to a controller through #Html.ActionLink. Basically user will be selecting start date , end date & phase number which on clicking a button exports the whole table into an excel. Below i am attaching the code of js, html, cs files.
js code:
<script type="text/javascript">
$(document).ready(function () {
$("#departing").datepicker({ dateFormat: 'yy-mm-dd' });
$("#returning").datepicker({ dateFormat: 'yy-mm-dd' });
$("button").click(function () {
var selected = $("#dropdown option:selected").text();
var departing = $("#departing").val();
var returning = $("#returning").val();
});
});
var selPhaseNumber = "A";
$(document).ready(function () {
//fetch and bind the year dropdown list
$('input[type=radio][name=rdbPhase]').change(function () {
if ($(this).val() == "Phase I") {
selPhaseNumber = "I";
}
else if ($(this).val() == "Phase II") {
selPhaseNumber = "II";
}
else {
selPhaseNumber = "A";
}
})
})
</script>
html code:
<div class="col-lg-6">
<div class="col-lg-3">#Html.ActionLink("Export to Excel", "ExportSubmittedTicketToExcel", "ExportExcel", null, new { #class = "btn btn-primary", #id = "btnExport"})</div>
</div>
(call should be something like this)
(api/ProjectBilling/SubmittedExportBillDetails/" + startdate + '/' + enddate + '/' + selPhaseNumber)
controller code:
[Route("ExportExcel/ExportSubmittedTicketToExcel/")]
public ActionResult ExportSubmittedTicketToExcel(string MemberName)
{
try
{
if (System.Web.HttpContext.Current.Session["DisplayName"] != null)
{
List<ExportExcelModelSubmitted> Result = new List<ExportExcelModelSubmitted>();
using (var client = new HttpClient())
{
int UserID = Convert.ToInt32(System.Web.HttpContext.Current.Session["CurrentUserID"]);
client.BaseAddress = new Uri(WebApiURL);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/ProjectBilling/SubmittedExportBillDetails/" + startdate + '/' + enddate + '/' + selPhaseNumber).Result;
if (response.IsSuccessStatusCode)
{
Result = response.Content.ReadAsAsync<List<ExportExcelModelSubmitted>>().Result;
}
else
{
string returncode = response.StatusCode.ToString();
return Content("<script language='javascript' type='text/javascript'>alert('" + returncode + "');</script>");
}
}
DataTable dt = new DataTable();
dt = Result.ToDataTable();
MemoryStream stream = new MemoryStream();
using (ExcelPackage pck = new ExcelPackage(stream))
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("BillingDetails");
ws.Cells["A1"].LoadFromDataTable(dt, true);
ws.Cells.AutoFitColumns();
using (ExcelRange rng = ws.Cells[1, 1, 1, dt.Columns.Count])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid;
rng.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(79, 129, 189));
rng.Style.Font.Color.SetColor(System.Drawing.Color.White);
}
pck.SaveAs(stream);
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=SubmittedBilling.xls");
Response.BinaryWrite(stream.ToArray());
Response.End();
}
return View();
}
else
{
return RedirectToAction("Login", "Home");
}
}
catch (Exception ex)
{
throw ex;
}
}
You can do it by Ajax Call also
[Route("ExportExcel/ExportSubmittedTicketToExcel/")]
public ActionResult ExportSubmittedTicketToExcel(datetime startDate,datetime endDate,string phaseNumber)
{
//logic
string fullPath = Path.Combine(Server.MapPath("~/MyFiles"), file);
return File(fullpath, "application/vnd.ms-excel", file);
}
and
$ajax({
cache: false,
url: '/ExportExcel/ExportSubmittedTicketToExcel',
data: {'startDate':startdate,'endDate':enddate,'phaseNumber':selPhaseNumber}
success: function (data){
window.location = data.fullpath;
}
})

Input array is longer

I try to display data in grid view through web method and jquery function so i try this. I try to display gridview when user select value from drop-down and select dates from calendar
$(function () {
$('[ID*=search_data]').on('click', function () {
var fromdate = $('[ID*=fromdate]').val();
var todate = $('[ID*=todate]').val();
var regiondrop = $('[ID*=regiondrop] option:selected')[0].value;
var GridView1 = $('[ID*=GridView1]');
var obj = {};
obj.fromdate = fromdate;
obj.todate = todate;
obj.regiondrop = regiondrop;
Getdataa(obj);
});
});
function Getdataa(obj) {
//alert('1');
$.ajax({
type: "POST",
url: "WebForm1.aspx/search_data",
data: "{'fromdate':'" + obj.fromdate + "','todate':'" + obj.todate + "','regiondrop':'" + obj.regiondrop + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (result) {
$("#GridView1").empty();
if (result.d.length > 0) {
$("#GridView1").append(
"<tr><th>ID</th><th>OName</th><th>Reg No</th><th>Speed</th></tr>");
for (var i = 0; i < result.d.length; i++) {
$("#GridView1").append("<tr><td>" +
result.d[i].ID+ "</td> <td>" +
result.d[i].OName + "</td> <td>" +
result.d[i].Reg No+ "</td> <td>" +
result.d[i].Speed+ "</td></tr>");
}
}
else {
$("#GridView1").hide();
$("#Label1").text("No Data");
}
},
error: function (error) {
alert("error");
}
});
}
WebMethod
[WebMethod]
public static DataTable search_data(DateTime fromdate, DateTime todate, string regiondrop)
{
try
{
T1 ts = new T1();
var dq = (from vv in ts.tblVe
join rv in ts.tblRe on vv.ID equals rv.ID
join re in ts.tblReg on rv.RID equals re.RID
where
re.Region == regiondrop
&& re.StartDate <= fromdate
&& re.EndDate >= todate
orderby
vv.ID,
rv.OwnerName
select new
{
ID=rv.ID,
OName = rv.OName ,
RegNo = rv.RegNo,
Speed = rv.Speed ,
}).ToList();
DataTable dt = new DataTable();
dt.Rows.Add(dq);
return dt;
}
catch (Exception)
{
throw new Exception();
}
}
in var dq.. dq show this data
[0] = { ID = 1, OName = "Khan", RegNo = "AJ-24",Speed = "124" } [1] = { ID = 2, OName = "Shah", RegNo = "AL-91",Speed = "95" }
UPDATE
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("OName", typeof(string));
dt.Columns.Add("RegNo", typeof(string));
dt.Columns.Add("Speed", typeof(string));
dt.Rows.Add(dq);
return dt;
and exception occur
Unable to cast object of type 'System.Collections.Generic.List`1[<>f__AnonymousType6`5[System.Int32,System.String,System.String,System.String,System.String]]' to type 'System.IConvertible'.Couldn't store <System.Collections.Generic.List`1[<>f__AnonymousType6`5[System.Int32,System.String,System.String,System.String,System.String]]> in ID Column.
You will have to add the columns in you datatable
dt.Columns.Add();
for more information : https://msdn.microsoft.com/en-us/library/hfx3s9wd(v=vs.110).aspx

angularjs post data to mvc controller in json format with multiple arrays

I am working on a project in which I have used angularjs and mvc.I am passing data from angular js controller to my mvc controller by $http.post().For now I am using single object/json array to retreive data like this -public bool UpdateIssueDetails(IssueBO issue).But I want that if I could do like this public public bool UpdateIssueDetails(IssueBO issue,List lstMembersToNotify).I want to send two json arrays from ny angular js controller to my above mvc controller method.
angularjs controller code
$scope.saveIssueDetails = function (issue) {
var milestoneId = "";
var milestoneName = "";
if ($scope.selectedIssue.Milestone== undefined) {
milestoneId = "";
milestoneName = "";
} else {
milestoneId = $scope.selectedIssue.Milestone.Id;
milestoneName = $scope.selectedIssue.Milestone.Name;
}
var arrMembersToNotify = [];
var arrMembersToNotifyNew = [];
var iCount = 0;
$("#membersToNotify input[type=checkbox]:checked").each(function () {
arrMembersToNotify = $(this).val().split("~");
arrMembersToNotifyNew.push({ "UserId": arrMembersToNotify[0], "UserDisplayName": arrMembersToNotify[1], "Email": arrMembersToNotify[2] });
});
var issueDetails =
{
Id: issue.Id,
ProjectId: issue.ProjectId,
ProjectName: issue.ProjectName,
IssueStatusId: $scope.selectedIssue.Status.Id,
StatusName: $scope.selectedIssue.Status.Name,
IssuePriorityId: $scope.selectedIssue.Priority.Id,
PriorityName: $scope.selectedIssue.Priority.Name,
AssignedUserId: $scope.selectedIssue.AssignedTo.Id,
AssigneeDisplayName: $scope.selectedIssue.AssignedTo.DisplayName,
IssueCategoryId: $scope.selectedIssue.Category.Id,
CategoryName: $scope.selectedIssue.Category.Name,
DueDate: $scope.selectedIssue.DueDate,
OwnerUserId: $scope.selectedIssue.OwnedBy.Id,
OwnerDisplayName: $scope.selectedIssue.OwnedBy.DisplayName,
IssueTypeId: $scope.selectedIssue.Type.Id,
IssueTypeName: $scope.selectedIssue.Type.Name,
IssueResolutionId: $scope.selectedIssue.Resolution.Id,
ResolutionName: $scope.selectedIssue.Resolution.Name,
MilestoneId: milestoneId,
MilestoneName: milestoneName,
Estimation: $scope.selectedIssue.Estimation,
Progress: $scope.selectedIssue.Progress,
};
var url = window.location.protocol + '//' + window.location.host + '/api/Issues' + '/UpdateIssueDetails/';
$http.post(url, [issueDetails, arrMembersToNotifyNew]).success(function (data, status, headers, config) {
if (data != '' || data.length >= 0 || data == true) {
//$scope.selectedIssue = issue;
//$scope.showIssueDetails($scope.selectedIssue);
$scope.GetAssignedIssues();
}
else if (data == '' || data == false) {
$scope.selectedIssue = null;
} else {
$scope.errors.push(data.error);
}
});
};
mvc controller code
[HttpPost]
[AuthenticationRequired]
public bool UpdateIssueDetails(IssueBO issue,List<IssueNotification> lstMembersToNotify)
{
try
{
//var issueDetails = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(issueAllDetails[0].ToString());
//List<Dictionary<string, string>> membersToNotifyDetails = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(issueAllDetails[1].ToString());
var membersToNotify = lstMembersToNotify.Select(membersToNotifyDetail =>
new IssueNotification()
{
UserId =membersToNotifyDetail.UserId,
Email =
membersToNotifyDetail.Email,
UserDisplayName =
membersToNotifyDetail.UserDisplayName
}).ToList();
var newIssue = new IssueBO
{
OwnerUserId = issue.OwnerUserId,
OwnerDisplayName = issue.OwnerDisplayName,
LastUpdatedUserId = SessionItems.UserId,
LastUpdaterDisplayName = SessionItems.DisplayName,
LastUpdatedOn = DateTime.Now,
ProjectId = issue.ProjectId,
ProjectName = issue.ProjectName,
Id = issue.Id,
AssignedUserId = issue.AssignedUserId,
AssigneeDisplayName = issue.AssigneeDisplayName,
IssueStatusId = issue.IssueStatusId,
StatusName = issue.StatusName,
Progress = issue.Progress,
IssuePriorityId = issue.IssuePriorityId,
PriorityName = issue.PriorityName,
IssueTypeId = issue.IssueTypeId,
IssueTypeName = issue.IssueTypeName,
IssueCategoryId = issue.IssueCategoryId,
CategoryName = issue.CategoryName,
IssueResolutionId = issue.IssueResolutionId,
ResolutionName = issue.ResolutionName,
DueDate = issue.DueDate,
Estimation = issue.Estimation,
MilestoneId = issue.MilestoneId,
MilestoneName = issue.MilestoneName
};
var result = BLL.AdminLayer.UpdateIssueDetail(newIssue, membersToNotify);
return result.IsSuccessful && result.Result;
}
catch (Exception ex)
{
BLL.Base.BaseLayer.WriteApplicationLog(ex);
return false;
}
}
I am passing two json array from my angularjs controller like this-$http.post(url, [issueDetails, arrMembersToNotifyNew]).success(function (data, status, headers, config).But I am getting error trying this.Please suggest how to achieve this.Thanks
You need to pass data to the action by using JSON.stringify()
$http.post(url, JSON.stringify({ issue: issueDetails,
lstMembersToNotify: arrMembersToNotifyNew
});
Post it as properties of an object.
$http.post(url, { issue: issueDetails, lstMembersToNotify: arrMembersToNotifyNew });

Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action

This is my action in controller. Which return a List> converting into DataSourceResult.and also Serializing into Json.
[HttpPost]
public ActionResult GetMissingShiftData([DataSourceRequest]DataSourceRequest request)
{
DataTable dtResponse = new DataTable();
var dynamicList = new List<dynamic>();
var myMainList = new List<List<dynamic>>();
List<DataSourceResult> viewResultList = new List<DataSourceResult>();
string RigNumber = string.IsNullOrWhiteSpace( resultData.Filter.SelectedRig.RigNumber) || resultData.Filter.SelectedRig.RigNumber == "ALL" ? "" : resultData.Filter.SelectedRig.RigNumber;
DataSet response = MissingShiftsReportData.GetData(Convert.ToDateTime(resultData.Filter.DateStart), Convert.ToDateTime(resultData.Filter.DateEnd), ConnString, RigNumber);
foreach (DataTable dt in response.Tables)
{
dtResponse = dt;
string[] columnNames = dtResponse.Columns.Cast<DataColumn>().Select(x => x.ColumnName).ToArray();
foreach (DataRow dr in dtResponse.Rows)
{
dynamic myObj = new ExpandoObject();
var p = myObj as IDictionary<string, object>;
Regex rgx = new Regex("[^a-zA-Z0-9]");
for (int i = 0; i < columnNames.Length; i++)
{
string name = dr.Table.Columns[i].ColumnName.Replace(" ", String.Empty);
name = name.Replace(".", String.Empty);
name = name.Replace("(", String.Empty);
name = name.Replace(")", String.Empty);
name = rgx.Replace(name, "");
p[name] = dr[i];
}
dynamicList.Add(p);
}
myMainList.Add(dynamicList);
}
DataSourceResult viewResult = myMainList.ToDataSourceResult(request);
string JsonViewData = JsonConvert.SerializeObject(viewResult.Data);
return new ContentResult { Content = JsonViewData, ContentType = "application/json", ContentEncoding = Encoding.UTF8 };
}
And this is the async call I am doing with Jqery.while I am trying to bind a data source it shows "data[0].Data" is "undefined". How can I make use of 'data'.
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var list = data[0].Data;
var dataSource = new kendo.data.DataSource({
data: data[0].Data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});
You are serializing an array (the Data property) and don't need to use the Data field at the client-side:
$.ajax({
url: "GetMissingShiftData",
type: "post",
datatype: 'json',
success: function (data) {
var dataSource = new kendo.data.DataSource({
data: data
});
dataSource.read();
return false;
},
error: function (msg) {
toastr.error("Error: " + msg.statusText);
}
});

Categories