pass JsonResult object from javascript function in View to Controller - javascript

How can I pass JsonResult object from javascript function in View to Controller Action without Ajax call - just javascript - window.location.href = url?
I get JsonResult object from Controller Action to javascript function via Ajax call. Then I want to pass this object back to other Controller Action but I get object with null reference properties.
My javascript function in View:
function order(model) {
$('#details-container').html("<h2>Loading Complete Frame Module. Please wait...</h2>");
$.p({
url: '#Url.Action("CompleteFrameBrandDetails", "PacCompleteFrame")',
data: { item: model },
success: function (xml) {
if (xml.Success) {
$.p({
url: '#Url.Action("GlassCompleteFrame", "PacModule")',
data: JSON.stringify({ b2bXml: xml.Data }),
success: function (model) {
var pacModuleModel = {
Mode: model.Data.Mode,
IframeUrl: model.Data.IframeUrl.toString(),
CustomerNumber: model.Data.CustomerNumber.toString(),
ReadOnly: model.Data.ReadOnly,
GlassXml: model.Data.GlassXml.toString(),
Price: parseFloat(model.Data.Price),
Comission: model.Data.Comission.toString(),
Permissions: null,
Language: model.Data.Language.toString()
};
// here are all values in model.Data correct
// but then I can't figure out how to pass it to Controller Action without Ajax call - just with javascript command
var url = '#Url.Action("GlassCompleteFrameView", "PacModule", "__view__")';
window.location.href = url.replace("__view__", model.Data); //pacModuleModel
}
});
} else {
$.alert({
message: 'error while trying to load xml details'
});
}
}
});
}
My Controller Action:
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get object module but
// model.CustomerNumber = null
// model.GlasXml = null
// model.Price = null
// ...
return View("Glass", model);
}
I have also Model like this for automatic Json binding but dont work:
public enum ModuleMode
{
ByProduct,
ByRecipe
}
public partial class PacModuleModel
{
private PacPermissionModel permissionModel;
public ModuleMode Mode { get; set; }
public string IframeUrl { get; set; }
public string CustomerNumber { get; set; }
public bool ReadOnly { get; set; }
public string GlassXml { get; set; }
public double? Price { get; set; }
public string Comission { get; set; }
public PacPermissionModel Permissions
{
get
{
if (permissionModel == null)
{
permissionModel = new PacPermissionModel();
}
return permissionModel;
}
}
public string Language { get; set; }
}

Try this in controller
public JsonResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get object module but
// model.CustomerNumber = null
// model.GlasXml = null
// model.Price = null
// ...
return Json(model, JsonRequestBehavior.AllowGet);
}

The problem was in model. It was more than 45000 char long. Now I use Session variable to get model in GlassCompleteFrameView(PacModuleModel model) and works perfect.
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
model = Session["xml"] as PacModuleModel;
return View("Glass", model);
}

Related

Some elements from JSON object passed to MVC controller are NULL

I am trying to pass a JSON object to my MVC controller action via POST. The controller action is called but some elements of the object are NULL. The 'ArticleKey' is there but the 'MeasureDefinitions' are NULL (see below).
Here is the object which I am trying to parse (it gets appended with more values by the user):
var articleValues = [
{
'ArticleKey': {
'ArticleNo': 'ArticleNo',
'CustomerName': 'CustomerName',
},
'MeasureDefinitions ': [
{
'DisplayIndex': 0,
'MeasureType': 'MeasureType',
'Percentage': 99.99,
'OriginalPercentage': 0
}
]
}
];
My model looks like this:
public class ArticleValuesModel
{
[Key]
public ArticleKey ArticleKey { get; set; }
public List<MeasureDefinition> MeasureDefinitions { get; set; }
public string ArticleDescription { get; set; }
public bool AddToList { get; set; }
}
public class ArticleKey
{
public string ArticleNo { get; set; }
public string CustomerName { get; set; }
}
public class MeasureDefinition
{
public long DisplayIndex { get; set; }
[Key]
public string MeasureType { get; set; }
public double Percentage { get; set; }
public double OriginalPercentage { get; set; }
}
Here is my controller action:
[HttpPost]
public ActionResult UpdateArticleValuesJson(List<Gui.Models.ArticleValuesModel> modelList)
{
return RedirectToAction("Index");
}
Here is my Ajax POST:
$('#btnSaveArticleValues').click(function() {
$.ajax({
url: "/ArticleList/UpdateArticleValuesJson",
contentType: "application/json;charset=utf-8",
dataType: "JSON",
type: "POST",
data: JSON.stringify(articleValues),
success: function() {
console.log("Saved");
},
error: function(e) {
console.log(e);
}
});
});
Can you please help me to make the 'MeasureDefinitions' list accessible in my controller?
Removing the extra spaces in my JSON object like indicated by the_lotus did help to resolve the problem.

Pass an Object from Angularjs to MVC controller and map to Class Object

I have an object in angularjs which I want to pass and map it to custom c# class in mvc controller. but whenever I am doing this class object is null completely.
$scope.Get = function () {
var EService = [{
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
}];
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
})
MVC Controller and Class:
[HttpPost]
public string Insert(ServicesMaster Service)
{
GIBCADBEntities gfientity = new GIBCADBEntities();
var record = "Sent"
return Json(record, JsonRequestBehavior.AllowGet);
} public class ServicesMaster
{
public string id { set; get; }
public string servicename { set; get; }
public string servicetype { set; get; }
public int? monthlyrental { set; get; }
public string serviceremarks { set; get; }
public byte servicestatus { set; get; }
public DateTime? activationdate { set; get; }
public DateTime? deactivationdate { set; get; }
}
The javascript variable/object "EService" is ok here, and when passing only the ServicesMaster object is created with null values and no data is mapped to it. I can send single string or any value from here but when sending a complete object its behaving like this.
You are passing an array from front end and fetching object from server end. just remove the "[" and "]" brace while set value to EService . Like :
$scope.Get = function () {
var Service = {};
Service = {
id: $scope.Id,
servicename: $scope.ServiceName,
servicetype: $scope.ServiceType,
monthlyrental: $scope.MonthlyRental,
serviceremarks: $scope.ServiceRemarks,
servicestatus: $scope.status,
activationdate: $scope.ActivationDate,
deactivationdate: $scope.DeActivationDate
};
$http.post('/TS/API/Insert', Service).then(function (res) {
debugger;
});
};
It should work now. :)

How to pass in nested data from the client to the controller

I have a form that has two sections. 3 input fields and another section with 10 checkboxes.
public class Customerproductdto
{
public string CustomerNumber { get; set; }
public string CustomerName { get; set; }
public string CustomerPhone { get; set; }
List<ProductDetails> GetAllChecked {get;set;}
}
public class ProductDetails
{
public string ProductName{ get; set; }
}
Here is jquery code I am using to get all the values of the checkboxes that were
checked on my form. They are about 10 and users could check everything.
var yourArray[]
$("input:checkbox[name=type]:checked").each(function(){
yourArray.push($(this).val());
});
Here is javascript that I use to collect the data and pass to my controller.
How can I pass in my array here all in one shot?
var objdata =
({
CustomerNumber: txtcustnumber,
CustomerName: txtcustname,
CustomerPhone: txtphone
//How do I pass the yourArray here?
});
var url = "#Url.Action("WriteToDb", "Home")";
var completeData = JSON.stringify({ 'Information': objdata });
$.get(url, { 'objdata': completeData }, function (data) {
$('#mainListContent').html(data);
});
Please note that I will like to deserialize this once I get to the controller.
Here is the method.
public ActionResult WriteToDb(string objdata)
{
Customerproductdto getAllTaskSaved = null;
try
{
var stripOffObjectName = JObject.Parse(objdata)["Information"];
var cleanedData = JsonConvert.DeserializeObject<Customerproductdto>(stripOffObjectName.ToString());
getAllTaskSaved = _dtcDataService.WriteTaskToDb(cleanedData, "Add");
}
catch (Exception ex)
{
logger.Error(ex);
}
return PartialView("_Taskdisplay", getAllTaskSaved);
}

KendoUI treeview children are displayed as undefined

I have a treeview in kendoUI in which main nodes are calling into an mvc controller and that controller looks to whether there is an nullable id passed in and then uses a different model.
What I hit the url : http://localhost:2949/Report/GetReportGroupAssignments
I see this JSON
[
{"Id":1,"ReportGroupName":"Standard Reports","ReportGroupNameResID":null,"SortOrder":1},
{"Id":2,"ReportGroupName":"Custom Reports","ReportGroupNameResID":null,"SortOrder":2},
{"Id":3,"ReportGroupName":"Retail Reports","ReportGroupNameResID":null,"SortOrder":3},
{"Id":4,"ReportGroupName":"Admin Reports","ReportGroupNameResID":null,"SortOrder":5},
{"Id":5,"ReportGroupName":"QA Reports","ReportGroupNameResID":null,"SortOrder":4}
]
Now my mvc controller looks like this
public JsonResult GetReportGroupAssignments(int? id)
{
var model = new List<ReportGroup>();
var defModel = new List<ReportDefinition>();
try
{
if (id == null)
{
model = _reportService.GetReportGroups("en-us").ToList();
return Json(model, JsonRequestBehavior.AllowGet);
}
else
{
defModel = _reportService.GetReportDefinitions().Where(e=>e.ReportGroupID ==Convert.ToInt32(id)).ToList();
return Json(defModel, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
Logger.Error(ex, "Error loading LoadReportList.");
return null;
}
}
My Kendo javascript looks like the following:
var serviceRoot = "/Report"; // "//demos.telerik.com/kendo-ui/service";
homogeneous = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: serviceRoot + "/GetReportGroupAssignments", //"/LoadReportTree", // "/Employees",
dataType: "json"
}
},
schema: {
model: {
id: "Id" //"ReportGroupName"
,hasChildren: "Id"
}
}
});
var treeview = $("#treeview").kendoTreeView({
expanded: true,
dragAndDrop: true,
dataSource: homogeneous,
dataTextField: "ReportGroupName"
}).data("kendoTreeView");
Seems that the calls (which I discovered that children records have a "load" method that it called behind the seens, so basically I pass in the ID in order to get the data from the other model ( table in db)
(Id is mapped with automapper to ReportGroupID )
So when i click to the left of "Standard Rports" I am getting all of these children as undefined, How do I get these to show up properly?
Update: My ReportDefinition class:
public class ReportDefinition {
public override int Id { get; set; }
public string ReportKey { get; set; }
public string ReportName { get; set; }
public int? ReportNameResID { get; set; }
public string ReportDef { get; set; }
public int? ReportDefinitionResID { get; set; }
public string ReportAssembly { get; set; }
public string ReportClass { get; set; }
public int ReportGroupID { get; set; }
public int AppID { get; set; }
public int SortOrder { get; set; }
public bool IsSubReport { get; set; }
}
I think your problem is that the class ReportDefinition does not have a property called: ReportGroupName. That is why TreeView displays 'undefined'.
Try adding this Property to your ReportDefinition class like:
public class ReportDefinition {
// Other Properties
// I guess this property is missing
public string ReportGroupName { get; set; }
}

Translate boolean to bool after Ajax call

Hi,
I have a .net class that contains a Boolean, this class is sent to client with AJAX. The problem is that if I just use :
if(MyClass.CheckedValue)
It will always be true even if the CheckedValue is false. I supose that it is instead checking if the object is set and if so it is true? Im note sure what type this Boolean propertie gets when returning to the javascript after AJAX?
I have also tried this :
var checked;
checked = Boolean(this.CheckedValue === 'true');
if (checked)
But this will also laways be true?
How do I handle this?
Edit1 :
The classes that is sent to client :
/// <summary>
/// Are set to client with Ajax to render a correct view of the
/// current category and filter settings
/// </summary>
public class GetCategoriesAndFiltersAjax
{
public GetCategoriesAndFiltersAjax()
{
Filters = new Filter();
}
public SelectList categoryList { get; set; }
public Filter Filters { get; set; }
public class Filter
{
public Filter()
{
DefaultFilters = new List<CategoryItemFilter>();
FilterList = new List<CategoryItemFilter>();
}
/// <summary>
/// Filters like buy, sell, let and so on
/// </summary>
public List<CategoryItemFilter> DefaultFilters { get; set; }
/// <summary>
/// All other filters that a category might be bound to
/// </summary>
public List<CategoryItemFilter> FilterList { get; set; }
}
}
public class CategoryItemFilter
{
private int _filterId = -1;
private string _clientElementId1;
private string _clientElementId2;
public FilterControlType FilterControlType { get; set; }
public string Title1 { get; set; }
public string Title2 { get; set; }
public string ClientElementId1
{
get { return _clientElementId1; }
set
{
_clientElementId1 = value;
}
}
public string ClientElementId2
{
get { return _clientElementId2; }
set
{
_clientElementId2 = value;
}
}
/// <summary>
/// Keep track of whitch filter it is
/// </summary>
public int FilterId
{
get { return _filterId; }
set { _filterId = value; }
}
#region Values
public Boolean CheckedValue { get; set; }
public string TextValue { get; set; }
public SelectList DropDownList1 { get; set; }
public SelectList DropDownList2 { get; set; }
#endregion
public PublicAdFilterKey PublicAdFilterKey { get; set; }
}
And this is how the AJAX method looks like on server :
public JsonResult GetCategoriesByParent(int id, Boolean editMode)
{
FilterModel filterModel = new FilterModel();
CategoryModel categoryModel = new CategoryModel();
List<ModelViewCategory> mvCategoryList = new List<ModelViewCategory>();
//List<AdCategory> categoryList;
FilterHandler filterHandler = new FilterHandler();
GetCategoriesAndFiltersAjax value = new GetCategoriesAndFiltersAjax();
try
{
value.categoryList = new SelectList(categoryModel.GetCategoriesByParent(id).ToArray(), "Id", "Name");
if (editMode)
value.Filters = filterHandler.ConvertFilterModelToAjaxCategoryFilter(filterModel.GetCategoryFilterByCategory(id), Biss.Views.ViewClasses.Filter.FilterType.Edit);
else
value.Filters = filterHandler.ConvertFilterModelToAjaxCategoryFilter(filterModel.GetCategoryFilterByCategory(id), Biss.Views.ViewClasses.Filter.FilterType.Display);
return this.Json(value, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
throw;
}
}
Edit 2 :
This is how the client looks like(not exacly but close, its alot more complicated)
$.ajax({
url: actionPath,
type: 'POST',
dataType: 'json',
data: ((typeof config.postData == "function") ? config.postData() : config.postData) || { id: $(source).val(), editMode: _filterInEditMode },
success: function (data) {
methods.reset();
$.each(data.categoryList, function () {
SetFilterSubEdit(data.DefaultFilters);
},
error: function () {
methods.showError();
}
});
function SetFilterSubEdit(data) {
$.each(data, function () {
if (data.CheckedValue)
$("#" + visibleElements[0]).attr('checked', checked);
}
}
Sorry, the problem was that the brackets was missing on client side.
if (data.CheckedValue){
}

Categories

Resources