View gets Json displayed on the page. not the data - json

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

Related

Clicking Ajax.ActionLink Produces a GET and a POST

Clicking a certain Ajax ActionLink in this app I just inherited produces a POST request AND a GET request (POST and then a GET immediately after). The first request hits the HttpPost method on the server, but the second request (the GET) throws a "404 (Not Found)" error in the browser. How do I stop the unwanted GET request? Where is it coming from?
If I change the method from POST to GET, the reverse occurs with the POST throwing the error instead of the GET.
I searched the application for similar requests to the same HttpPost method that were configured as GETs and there are none.
I searched for custom JavaScript that was attaching an extra click event to all links and there were no instances of that. Could there be other events that would produce the same result in this instance?
Chrome DevTools Screenshot
In DocumentManagementController.cs:
[HttpPost]
public ActionResult OpenPopup(string ntgLoadId) { ... }
In _GridLoadsAddendum.cshtml:
#Html.DevExpress().GridView(
settings =>
{
settings.Name = "DetailedGrid_" + Model.LoadId;
settings.Width = Unit.Percentage(100);
settings.Settings.ShowFilterRow = false;
settings.Settings.ShowGroupPanel = false;
settings.Settings.ShowFooter = false;
settings.Settings.ShowColumnHeaders = false;
settings.KeyFieldName = "NtgLoadId";
settings.Columns.Add(column =>
{
column.FieldName = "Status";
column.Caption = "Status";
column.Width = Unit.Pixel(83);
column.SetDataItemTemplateContent(c =>
{
ViewContext.Writer.Write(
Ajax.ActionLink(
DataBinder.Eval(c.DataItem, "Status").ToString(),
"OpenPopup",
"DocumentManagement",
new
{
ntgLoadId = c.KeyValue.ToString()
},
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ModalContainer",
AllowCache = false
},
new
{
#class = "status-link",
data_Toggle = "modal",
data_Target = "#ModalContainer",
data_backdrop = "static",
data_Keyboard = "false"
}).ToHtmlString());
});
});
settings.Styles.Table.CssClass = "MVCxGridViewTable";
settings.Styles.Header.CssClass = "MVCxGridViewHeader";
settings.Styles.Cell.CssClass = "MVCxGridViewCell addendum";
settings.Styles.CommandColumnItem.CssClass = "MVCxGridViewCell";
settings.Styles.AlternatingRow.CssClass = "MVCxGridViewAlternatingRow addendum";
settings.Styles.PagerBottomPanel.CssClass = "MVCxGridViewPagerBottomPanel";
settings.Settings.ShowFooter = false;
settings.ClientSideEvents.BeginCallback = "initechPortal.carrierPaymentStatusHelper.gridResultsHelper.beginCallback";
settings.CallbackRouteValues = new
{
Controller = "CarrierPaymentController",
Action = "GridLoadsAddendum",
Id = Model.LoadId
};
settings.DataBound = (sender, e) =>
{
MVCxGridView gv = sender as MVCxGridView;
gv.Visible = gv.VisibleRowCount > 0;
};
}).BindToLINQ(
string.Empty,
string.Empty,
new EventHandler<DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs>(
(s, e) =>
{
e.QueryableSource = Model.CarrierPaymentResultData;
e.KeyExpression = "ntgLoadId";
})).GetHtml();

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

kendo treeview with new data source

Ok, so I have this situation here:
A CSHTML view with a kendo tree in it:
#(Html.Kendo().TreeView()
.Name("treeview")
.DataTextField("Name")
.DataSource(d => d.Read(r => r.Action("WorkedHours", "TaskManager")))
.Events(e => e.Select("onSelect"))
)
to the right of that there is a kendo grid. and above the tree there is a (kendo) dropdown list to select a user.
this is the controller method called by the tree:
public JsonResult WorkedHours(uint? id)
{
DocObjectArray docObjects = null;
if (id == null)
{
// get root elements
var loggedInUserRef = OmanagerUtils.GetInstance().LoggedInUser;
if (loggedInUserRef != null && loggedInUserRef.GetObject() != null && loggedInUserRef.GetObject().SubObjects != null)
{
for (int i = 0; i < loggedInUserRef.GetObject().SubObjects.GetLength(); i++)
{
var item = loggedInUserRef.GetObject().SubObjects.GetAt(i);
if (item.ToString() == TaskManagerConstants.UserWorkHours)
{
docObjects = item.TreeSubObjects;
break;
}
}
}
}
else
{
// get sub objects of a root object
var rootObj = new DocObjectRef((int)id);
docObjects = rootObj.GetObject().TreeSubObjects;
}
var returnDocObjects = new List<OmanagerItem>();
for (int i = 0; i < docObjects.GetLength(); i++)
{
var item = docObjects.GetAt(i);
var hasChildren = true;
if (item.TreeSubObjects == null)
{
hasChildren = false;
}
else
{
if (item.TreeSubObjects.GetLength() == 0)
{
hasChildren = false;
}
}
var listItem = new OmanagerItem
{
hasChildren = hasChildren,
id = item.GetOID(),
Name = item.ToString()
};
returnDocObjects.Add(listItem);
}
return Json(returnDocObjects, JsonRequestBehavior.AllowGet);
}
now, the problem is that i have to be able to select a user from the dropdown list and refresh the tree with this new data.
$("#employee").kendoDropDownList({
change: function () {
var postdata = {
id:$("#employee").val()
}
$.ajax({
url: "TaskManager/WorkedHours",
cache: false,
type: "POST",
data: postdata,
success: function (data) {
$("#treeview").data("kendoTreeView").setDataSource(data);
},
});
}
});
the problem is what do i do with this data? because my attempt did not really work.
many thanks.
You can use OutputCache attribute on WorkedHours action:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
public JsonResult WorkedHours(uint? id)
{
// rest of method
}
It helped in my case :)
Maybe this little snippet is of any help to you.
Similar to your code in the change event of my dropdown I'm calling a function that will change the request data of my TreeView DataSource.
After changing it, it calls the read() handler of the datasource so it re-reads the data:
function loadTreeViewData() {
var employee = $('#employee').getKendoDropDownList().dataItem();
WorkedHoursDataSource.transport.options.read.data = {Employee_Id:employee.id};
WorkedHoursDataSource.read();
}

JsonResult in MVC3 app need to add a default entry at top of results...

I need to insert a default value at the top of the result I have as below....
Can someone give me a clue how to do it with an anonymous type?
public JsonResult GetThingsForStuff(string stuff)
{
var things= from c in db.MYTABLE
where c.idofstuff == stuff
select new { id = c.realid, name = c.realname};
return Json(things, JsonRequestBehavior.AllowGet);
}
In my controller I do this initially by
List<SelectListItem> items3 = new SelectList(db.MYTABLE.ToList().Distinct(), "realid", "realname").ToList();
items3.Insert(0, (new SelectListItem { Text = "Select Me", Value = "0" }));
ViewBag.Things = items3;
by I have a javascript function reloading this dropdownlist based on the selected "stuff" and I need this default back at the top.
Any help would be greatly appreciated.
Thanks,
David
You could concatenate them:
public JsonResult GetThingsForStuff(string stuff)
{
var things = db
.MYTABLE
.Where(x => x.idofstuff == stuff)
.ToList()
.Select(x => new SelectListItem
{
Value = x.realid.ToString(),
Text = x.realname
});
var items = new[] { new SelectListItem { Text = "Select Me", Value = "0" } }
.Concat(things);
return Json(items, JsonRequestBehavior.AllowGet);
}

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.